#!/usr/bin/env python3
"""Validate PRISM-DIRECTOR-IR-1.0 authority, traceability, XYZ and handoffs."""

from __future__ import annotations

import argparse
import copy
import importlib.util
import json
import math
import sys
from pathlib import Path
from typing import Any

try:
    import yaml
except ImportError:  # pragma: no cover
    yaml = None


SCHEMA = "PRISM-DIRECTOR-IR-1.0"
ALLOWED_CONTROLLERS = {"WANFU", "PRISM_STANDALONE"}
CLAIM_STATUSES = {"RELEASE_CANDIDATE", "TESTED"}
CREATIVE_OWNED_FIELDS = {
    "concept_truth",
    "story_truth",
    "plot",
    "character_truth",
    "world_truth",
    "structure",
    "information_truth",
    "climax",
    "scene_outcome",
    "beat_truth",
    "relationship_truth",
    "promise_payoff",
}
ALLOWED_FIELD_OWNERS = {
    **{field: "CREATIVE_TO_NARRATIVE" for field in CREATIVE_OWNED_FIELDS},
    "longform_review": "EVALUATOR_ONLY",
    "screenplay_format": "CREATIVE_MEDIA_RENDERER",
    "cross_scene_continuity": "CONTINUITY_GUARD",
    "script_doctor_report": "EVALUATOR_ONLY",
    "xyz_blocking": "PRISM_SPATIAL_COMPILER",
    "composition": "MIRROR_COMPOSITION_SUPPORT",
    "prop_continuity": "WANFU_PROP_SUPPORT",
    "performance": "PERFORMANCE_SUPPORT",
    "camera": "CAMERA_STRATEGY",
    "edit": "EDIT_TRANSITION_COMPILER",
    "sound": "SOUND_COMPILER",
    "shot_order": "PRISM_DIRECTOR_COMPILER",
    "final_transition": "EDIT_TRANSITION_COMPILER",
    "asset_continuity": "CONTINUITY_GUARD",
    "final_shot_format": "DIRECTOR_SCRIPT_COMPILER",
}
ALLOWED_SUPPORT_MODULES = {
    "PRISM_XYZ",
    "MIRROR_COMPOSITION",
    "PROP_CONTINUITY",
    "PERFORMANCE_MICROEXPRESSION",
    "CONTINUITY_GUARD",
    "SOUND_EDIT",
    "SCENE_BLOCKING",
    "FILM_CREW_COMPILER",
}
PRODUCTION_CONSTRAINT_IDS = {
    "PROD_ATOMIC_ONE_PRIMARY_ACTION",
    "PROD_NO_IDENTITY_OR_HAND_SWITCH",
    "PROD_PLATFORM_DURATION_LIMIT",
    "PROD_BUDGET_LIMIT",
    "PROD_LOCATION_ACCESS_LIMIT",
    "PROD_ACTOR_SAFETY_LIMIT",
}
COMPOSITION_CATALOG = {
    "COMP_DIAGONAL": "MAIN",
    "COMP_STABLE_TRIANGLE": "MAIN",
    "COMP_FRAME_WITHIN_FRAME": "MAIN",
    "COMP_CENTERED": "MAIN",
    "COMP_DEPTH_LAYERING": "SPATIAL",
    "COMP_FOREGROUND_OCCLUSION": "SPATIAL",
    "COMP_PILLAR_REVEAL": "SPATIAL",
    "COMP_EYE_PATH": "REINFORCEMENT",
    "COMP_PROP_REACTION_CENTER": "REINFORCEMENT",
    "COMP_EXIT_MOTIF": "REINFORCEMENT",
}
FEIRAN_ALLOWED_RULES = {
    "FEIRAN_STIMULUS_MICROEXPRESSION",
    "FEIRAN_LIVING_GROUP_REACTION",
    "FEIRAN_FUNCTIONAL_FOREGROUND",
    "FEIRAN_SUBJECT_ANCHOR",
    "FEIRAN_ENVIRONMENT_FEEDBACK",
    "FEIRAN_IMPACT_TRIGGERED_SHAKE",
}
FEIRAN_RULE_SCOPES = {
    "FEIRAN_STIMULUS_MICROEXPRESSION": "performance.microexpression",
    "FEIRAN_LIVING_GROUP_REACTION": "performance.group_reaction",
    "FEIRAN_FUNCTIONAL_FOREGROUND": "composition.foreground",
    "FEIRAN_SUBJECT_ANCHOR": "composition.subject_anchor",
    "FEIRAN_ENVIRONMENT_FEEDBACK": "performance.environment_feedback",
    "FEIRAN_IMPACT_TRIGGERED_SHAKE": "camera.impact_feedback",
}
DIRECTOR_LAYER_ORDER = {"SCREENPLAY": 2, "DIRECTOR_SHOOTING_SCRIPT": 3, "ATOMIC_VIDEO_PACKAGE": 4}
CLAIM_TEMPLATES = {
    "RELEASE_CANDIDATE": ("STATIC_STRUCTURE_ONLY", "STRUCTURAL_RC", "CLAIM_RC_STATIC_ONLY"),
    "TESTED": ("REGISTERED_PLATFORM_MODEL", "TESTED_IN_REGISTERED_SCOPE", "CLAIM_TESTED_REGISTERED_SCOPE_ONLY"),
}
METHOD_CATALOG = {
    "SHANYIN_ORIGINAL_LONGFORM_REVIEW": "SHANYIN",
    "SHANYIN_CONCEPT_LAB": "SHANYIN",
    "SHANYIN_FORMAT_SCALE_VIEW": "SHANYIN",
    "SHANYIN_DUAL_TRACK_AUDIT": "SHANYIN",
    "SHANYIN_CHECKPOINT_VIEW": "SHANYIN",
    "MIRROR_COMPOSITION_SUPPORT": "MIRROR",
    "FEIRAN_SELECTIVE_PERFORMANCE_SUPPORT": "FEIRAN",
}
METHOD_REJECTION_REASONS = {"SOURCE_BODY_MISSING", "FIELD_AUTHORITY_CONFLICT", "EVIDENCE_LEVEL_INSUFFICIENT", "OUT_OF_SCOPE"}
SHANYIN_GAP_MANIFEST_ID = "SHANYIN-GAP-MANIFEST-001"
SHANYIN_GAP_RECEIPT_ID = "SHANYIN-GAP-RECEIPT-001"
SHANYIN_SOURCE_MANIFEST_ID = "SHANYIN-SOURCE-MANIFEST-001"
SHANYIN_SOURCE_RECEIPT_ID = "SHANYIN-SOURCE-RECEIPT-001"
SHANYIN_VERIFIED_HASH = "5be8e1b9fab372c4d418a4e79c19d20eafc5af217020a1a7a1857d89d5a774ba"
NOTICE_TEMPLATE_ID = "NOTICE_SOURCE_BODY_MISSING_FALLBACK"
NOTICE_TEMPLATE_TEXT = "山音正文缺失，本轮未调用其专属流程，改用Creative与棱镜导演编译器。"
DIRECTOR_ROOT_KEYS = {
    "schema_version",
    "runtime_context",
    "authority_contract",
    "source_registry",
    "source_contract",
    "claim_contract",
    "evidence_registry",
    "load_plan",
    "shanyin_runtime_receipt",
    "request_contract",
    "layer_receipts",
    "decision_registry",
    "project",
    "action_registry",
    "reaction_target_registry",
    "av_policy",
    "style_contract",
    "sound_registry",
    "performance_units",
    "scenes",
}
PROJECT_KEYS = {
    "project_id",
    "mode",
    "delivery_profile",
    "duration",
    "aspect_ratio",
    "wardrobe_policy",
    "authorized_changes",
    "frozen_assets",
    "asset_registry",
    "frozen_asset_bindings",
    "production_constraints",
}
EVIDENCE_ROLE_TYPES = {
    "ABC_CASE": "A_B_C_CASE",
    "BLIND_REVIEW": "BLIND_REVIEW",
    "FAILURE_LEDGER": "FAILURE_LEDGER",
    "REGRESSION_RUN": "REGRESSION_RUN",
}
SUPPORT_OWNER_REQUIREMENTS = {
    "PRISM_XYZ": {"xyz_blocking": "PRISM_SPATIAL_COMPILER"},
    "SCENE_BLOCKING": {"xyz_blocking": "PRISM_SPATIAL_COMPILER"},
    "MIRROR_COMPOSITION": {"composition": "MIRROR_COMPOSITION_SUPPORT"},
    "PROP_CONTINUITY": {"prop_continuity": "WANFU_PROP_SUPPORT"},
    "PERFORMANCE_MICROEXPRESSION": {"performance": "PERFORMANCE_SUPPORT"},
    "CONTINUITY_GUARD": {
        "cross_scene_continuity": "CONTINUITY_GUARD",
        "asset_continuity": "CONTINUITY_GUARD",
    },
    "SOUND_EDIT": {"sound": "SOUND_COMPILER", "edit": "EDIT_TRANSITION_COMPILER"},
    "FILM_CREW_COMPILER": {"camera": "CAMERA_STRATEGY", "edit": "EDIT_TRANSITION_COMPILER", "sound": "SOUND_COMPILER"},
}
AXIS_RELATIONS = {"SAME_SIDE", "CROSS", "NEUTRAL_AXIS", "NEW_AXIS_ESTABLISHED_BY_SCENE_CHANGE"}
SCREEN_DIRECTIONS = {
    "left-to-right",
    "right-to-left",
    "left-to-center",
    "right-to-center",
    "center-to-left",
    "center-to-right",
    "center-to-depth",
    "left-to-center-arc",
    "center-to-right-depth",
    "center-hold",
}
UV_UNITS = {"normalized-frame", "pixel"}
ENTITY_TARGET_TYPES_REQUIRING_CONTACT = {"handheld-prop", "rigid-environment", "character"}
EVIDENCE_TYPES = {
    "VISIBLE_ACTION",
    "VISIBLE_STATE",
    "AUDIBLE_CUE",
    "SPATIAL_RELATION",
    "PROP_STATE",
    "PERFORMANCE_CHANGE",
    "WORLD_EVENT",
}
SHANYIN_DECISIONS = {"INVOKE_AS_SECONDARY_ADAPTER", "BLOCK_MODULE", "CONTINUE_WITH_EVIDENCE_FALLBACK", "BLOCK_DELIVERY"}
SHANYIN_STATUSES = {"SOURCE_VERIFIED", "SOURCE_BODY_MISSING"}
SOUND_PHASES = {"ONSET", "SUSTAIN", "DECAY"}
SOUND_CLASSES = {"NOT_MUSIC", "DIEGETIC_MUSIC", "SCORE"}
FORBIDDEN_METHOD_CLAIM_TOKENS = {
    "FEIRAN_ALL_HARD",
    "斐然全部硬规则",
    "MIRROR_FULL_LIBRARY",
    "镜律全加载",
    "SHANYIN_EIGHT_STEPS",
    "山音八步",
    "SHANYIN_FIVE_STEPS",
    "山音五步",
}


def load_document(path: Path) -> dict[str, Any]:
    text = path.read_text(encoding="utf-8")
    if path.suffix.lower() == ".json":
        data = json.loads(text)
    else:
        if yaml is None:
            raise RuntimeError("PyYAML is required for YAML input; use JSON instead")
        data = yaml.safe_load(text)
    if not isinstance(data, dict):
        raise ValueError("root must be an object")
    return data


def numeric(value: Any) -> bool:
    return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)


def coord(value: Any) -> bool:
    return isinstance(value, list) and len(value) == 3 and all(numeric(item) for item in value)


def required(mapping: Any, keys: list[str], prefix: str, errors: list[str]) -> None:
    if not isinstance(mapping, dict):
        errors.append(f"{prefix}: must be an object")
        return
    for key in keys:
        if mapping.get(key) in (None, "", [], {}):
            errors.append(f"{prefix}: missing {key}")


def flatten(value: Any, prefix: str = "") -> dict[str, Any]:
    if isinstance(value, dict):
        out: dict[str, Any] = {}
        for key, item in value.items():
            path = f"{prefix}.{key}" if prefix else str(key)
            out.update(flatten(item, path))
        return out
    if isinstance(value, list):
        return {prefix: value}
    return {prefix: value}


def diff_paths(left: Any, right: Any, prefix: str = "") -> set[str]:
    a, b = flatten(left, prefix), flatten(right, prefix)
    return {path for path in set(a) | set(b) if a.get(path) != b.get(path)}


def allowed(path: str, whitelist: list[str]) -> bool:
    return any(path == item or path.startswith(f"{item}.") for item in whitelist)


def prop_map(assets: dict[str, Any]) -> dict[str, dict[str, Any]]:
    result: dict[str, dict[str, Any]] = {}
    for prop in assets.get("hand_props", []) or []:
        if isinstance(prop, dict) and prop.get("prop_id"):
            result[str(prop["prop_id"])] = prop
    return result


def softbody_map(assets: dict[str, Any]) -> dict[str, dict[str, Any]]:
    result: dict[str, dict[str, Any]] = {}
    for body in assets.get("softbody", []) or []:
        if isinstance(body, dict) and body.get("softbody_id"):
            result[str(body["softbody_id"])] = body
    return result


def entity_base(value: Any) -> str:
    return str(value or "").split(".", 1)[0].split(":", 1)[-1]


def within_bounds(point: Any, bounds: Any) -> bool:
    if not coord(point) or not isinstance(bounds, dict) or not coord(bounds.get("min")) or not coord(bounds.get("max")):
        return False
    return all(bounds["min"][index] <= point[index] <= bounds["max"][index] for index in range(3))


def state_delta_keys(delta: Any) -> set[str]:
    if not isinstance(delta, dict):
        return set()
    return {str(key) for key, value in delta.items() if isinstance(value, dict) and value.get("before") != value.get("after")}


def get_path(mapping: Any, path: str) -> Any:
    current = mapping
    for part in str(path).split("."):
        if not isinstance(current, dict) or part not in current:
            return None
        current = current[part]
    return current


def normalized_body_part(value: Any) -> str:
    return str(value or "").lower().replace("and-", "").replace("-and", "").replace("_", "-")


def source_gap_missing_shanyin(source_contract: dict[str, Any]) -> bool:
    gaps = source_contract.get("source_gaps", []) or []
    return any(
        ("SHANYIN" in json.dumps(gap, ensure_ascii=False).upper() or "山音" in json.dumps(gap, ensure_ascii=False))
        and ("MISSING" in json.dumps(gap, ensure_ascii=False).upper() or "缺失" in json.dumps(gap, ensure_ascii=False))
        for gap in gaps
    )


def authoritative_shanyin_status(data: dict[str, Any]) -> str | None:
    registry = data.get("source_registry")
    if not isinstance(registry, dict):
        return None
    item = registry.get("SHANYIN")
    return str(item.get("status")) if isinstance(item, dict) and item.get("status") else None


def normalized_source(value: Any) -> str:
    text = str(value or "").upper()
    if "FEIRAN" in text or "斐然" in text:
        return "FEIRAN"
    if "SHANYIN" in text or "山音" in text:
        return "SHANYIN"
    if "MIRROR" in text or "镜律" in text or "JINGLU" in text:
        return "MIRROR"
    return text


def recursive_keys(value: Any) -> set[str]:
    result: set[str] = set()
    if isinstance(value, dict):
        for key, item in value.items():
            result.add(str(key).lower())
            result.update(recursive_keys(item))
    elif isinstance(value, list):
        for item in value:
            result.update(recursive_keys(item))
    return result


def recursive_key_values(value: Any, wanted: set[str]) -> list[Any]:
    result: list[Any] = []
    if isinstance(value, dict):
        for key, item in value.items():
            if str(key).lower() in wanted:
                result.append(item)
            result.extend(recursive_key_values(item, wanted))
    elif isinstance(value, list):
        for item in value:
            result.extend(recursive_key_values(item, wanted))
    return result


def method_like(value: Any) -> bool:
    text = json.dumps(value, ensure_ascii=False).upper()
    return any(token.upper() in text for token in FORBIDDEN_METHOD_CLAIM_TOKENS)


def validate_authority(data: dict[str, Any], errors: list[str], warnings: list[str]) -> None:
    if data.get("schema_version") != SCHEMA:
        errors.append(f"schema_version must be {SCHEMA}")
    unknown_root_keys = set(data) - DIRECTOR_ROOT_KEYS
    if unknown_root_keys:
        errors.append(f"director root uses unregistered fields: {sorted(unknown_root_keys)}")

    runtime = data.get("runtime_context")
    required(runtime, ["embedded_in_wanfu", "parent_controller", "validation_mode"], "runtime_context", errors)
    if isinstance(runtime, dict):
        if not isinstance(runtime.get("embedded_in_wanfu"), bool):
            errors.append("runtime_context.embedded_in_wanfu must be boolean")
        if runtime.get("validation_mode") not in {"TEST_FIXTURE", "FORMAL_DELIVERY"}:
            errors.append("runtime_context.validation_mode must be TEST_FIXTURE or FORMAL_DELIVERY")

    authority = data.get("authority_contract")
    required(authority, ["controller", "controller_count", "field_owners"], "authority_contract", errors)
    if not isinstance(authority, dict):
        return
    if authority.get("controller") not in ALLOWED_CONTROLLERS:
        errors.append("authority_contract.controller must be WANFU or PRISM_STANDALONE")
    if authority.get("controller_count") != 1:
        errors.append("authority_contract.controller_count must equal 1")
    if isinstance(runtime, dict) and runtime.get("embedded_in_wanfu") is True:
        if authority.get("controller") != "WANFU" or runtime.get("parent_controller") != "WANFU":
            errors.append("embedded director runtime must use WANFU as the parent and sole controller")
    elif isinstance(runtime, dict) and authority.get("controller") == "PRISM_STANDALONE" and runtime.get("parent_controller") != "NONE":
        errors.append("standalone director runtime must declare parent_controller NONE")

    owners = authority.get("field_owners", {})
    if not isinstance(owners, dict) or not owners:
        errors.append("authority_contract.field_owners must be a non-empty object")
        owners = {}
    for field, owner in owners.items():
        if not isinstance(owner, str) or not owner.strip():
            errors.append(f"field owner must be one string: {field}")
        elif field not in ALLOWED_FIELD_OWNERS:
            errors.append(f"unknown field owner key: {field}")
        elif owner != ALLOWED_FIELD_OWNERS[field]:
            errors.append(f"field owner mismatch: {field} must be {ALLOWED_FIELD_OWNERS[field]}")
    for field in CREATIVE_OWNED_FIELDS:
        if owners.get(field) != "CREATIVE_TO_NARRATIVE":
            errors.append(f"Creative-owned field missing or reassigned: {field}")

    registry = data.get("source_registry")
    if not isinstance(registry, dict):
        errors.append("source_registry must be an object")
        registry = {}
    shanyin_source = registry.get("SHANYIN")
    required(shanyin_source, ["status", "source_version", "authorship_status", "manifest_id", "validation_receipt_id"], "source_registry.SHANYIN", errors)
    shanyin_status = shanyin_source.get("status") if isinstance(shanyin_source, dict) else None
    if shanyin_status not in SHANYIN_STATUSES:
        errors.append("SHANYIN status must be SOURCE_VERIFIED or SOURCE_BODY_MISSING")
    elif shanyin_status == "SOURCE_VERIFIED":
        if shanyin_source.get("source_hash") != SHANYIN_VERIFIED_HASH:
            errors.append("verified ShanYin source hash does not match the release evidence")
        if shanyin_source.get("source_version") != "VERSION_UNDECLARED":
            errors.append("verified ShanYin source must preserve VERSION_UNDECLARED")
        if shanyin_source.get("authorship_status") != "AUTHORSHIP_UNVERIFIED":
            errors.append("verified ShanYin source must preserve AUTHORSHIP_UNVERIFIED")
        if shanyin_source.get("manifest_id") != SHANYIN_SOURCE_MANIFEST_ID or shanyin_source.get("validation_receipt_id") != SHANYIN_SOURCE_RECEIPT_ID:
            errors.append("verified ShanYin source must bind the immutable source manifest IDs")
    elif shanyin_source.get("source_hash") is not None:
        errors.append("missing ShanYin body must use source_hash null")
    elif shanyin_source.get("manifest_id") != SHANYIN_GAP_MANIFEST_ID or shanyin_source.get("validation_receipt_id") != SHANYIN_GAP_RECEIPT_ID:
        errors.append("missing ShanYin source must bind the immutable gap manifest IDs")

    source = data.get("source_contract")
    required(
        source,
        ["source_ir_id", "source_ir_version", "frozen_story_core_id", "screenplay_layer_id", "screenplay_version", "active_sources"],
        "source_contract",
        errors,
    )
    if not isinstance(source, dict):
        source = {}
    for list_key in ("source_gaps", "candidate_rules_in_use", "rejected_rules"):
        if list_key not in source or not isinstance(source.get(list_key), list):
            errors.append(f"source_contract.{list_key} must be a list")
    active_sources = source.get("active_sources", []) or []
    if not isinstance(active_sources, list):
        errors.append("source_contract.active_sources must be a list")
        active_sources = []
    active_shanyin = any(normalized_source(item) == "SHANYIN" for item in active_sources)
    missing_gap = source_gap_missing_shanyin(source)

    receipt = data.get("shanyin_runtime_receipt")
    required(receipt, ["requested", "source_status", "source_version", "authorship_status", "decision", "invoked", "adapter_profile", "fallback", "notice_emitted", "source_manifest_id", "validation_receipt_id"], "shanyin_runtime_receipt", errors)
    if isinstance(receipt, dict):
        if receipt.get("decision") not in SHANYIN_DECISIONS:
            errors.append("unsupported ShanYin decision")
        if shanyin_status == "SOURCE_VERIFIED":
            if not active_shanyin or missing_gap:
                errors.append("verified ShanYin source must be active and cannot also be missing")
            if receipt.get("source_status") != "SOURCE_VERIFIED" or receipt.get("invoked") is not True:
                errors.append("verified ShanYin request requires invocation as a secondary adapter")
            if receipt.get("decision") != "INVOKE_AS_SECONDARY_ADAPTER" or receipt.get("adapter_profile") != "SHANYIN_DELTA_ONLY" or receipt.get("fallback") != "NONE":
                errors.append("verified ShanYin receipt must use the delta-only adapter profile")
            if receipt.get("source_version") != "VERSION_UNDECLARED" or receipt.get("authorship_status") != "AUTHORSHIP_UNVERIFIED":
                errors.append("ShanYin receipt must preserve source version and authorship uncertainty")
            if receipt.get("source_manifest_id") != SHANYIN_SOURCE_MANIFEST_ID or receipt.get("validation_receipt_id") != SHANYIN_SOURCE_RECEIPT_ID:
                errors.append("ShanYin runtime receipt must bind the verified source registry")
            if receipt.get("notice_emitted") is not False:
                errors.append("verified ShanYin invocation must not emit a missing-source notice")
        else:
            if active_shanyin:
                errors.append("missing ShanYin source cannot appear in active_sources")
            if not missing_gap:
                errors.append("missing ShanYin source must expose the authoritative source gap")
            if receipt.get("source_status") != "SOURCE_BODY_MISSING" or receipt.get("invoked") is not False:
                errors.append("ShanYin cannot be invoked while SOURCE_BODY_MISSING")
            if receipt.get("fallback") != "CREATIVE_PLUS_PRISM_DIRECTOR_COMPILER":
                errors.append("missing ShanYin body requires the declared Creative+Prism fallback")
            if receipt.get("requested") is True and receipt.get("notice_emitted") is not True:
                errors.append("requested missing ShanYin source requires a visible notice")
            if receipt.get("source_manifest_id") != SHANYIN_GAP_MANIFEST_ID or receipt.get("validation_receipt_id") != SHANYIN_GAP_RECEIPT_ID:
                errors.append("ShanYin runtime receipt must bind the missing-source registry")
        if receipt.get("decision") == "BLOCK_DELIVERY" and data.get("scenes"):
            errors.append("BLOCK_DELIVERY forbids formal scene delivery")
    forbidden_keys = {"shanyin_eight_steps", "shanyin_five_steps", "screenwriting_eight_steps", "director_five_steps", "五步正文", "八步正文"}
    if forbidden_keys & recursive_keys(data):
        errors.append("invented ShanYin five/eight-step body detected")

    candidates = source.get("candidate_rules_in_use", []) or []
    if not isinstance(candidates, list):
        errors.append("source_contract.candidate_rules_in_use must be a list")
        candidates = []
    for idx, rule in enumerate(candidates):
        label = f"source_contract.candidate_rules_in_use[{idx}]"
        required(rule, ["source_id", "rule_id", "enforcement", "field_scope"], label, errors)
        if isinstance(rule, dict):
            rule_id = str(rule.get("rule_id", ""))
            is_feiran = normalized_source(rule.get("source_id")) == "FEIRAN" or "FEIRAN" in rule_id.upper() or "斐然" in rule_id
            if not is_feiran or rule_id not in FEIRAN_ALLOWED_RULES:
                errors.append(f"{label}: unsupported Feiran candidate rule")
            if is_feiran and str(rule.get("enforcement", "")).upper() != "SOFT":
                errors.append("Feiran candidate rule cannot be promoted to HARD without evidence")
            if rule_id in FEIRAN_RULE_SCOPES and rule.get("field_scope") != FEIRAN_RULE_SCOPES[rule_id]:
                errors.append(f"{label}: Feiran rule field_scope exceeds its closed support field")
    rejected_rules = source.get("rejected_rules", []) or []
    if not isinstance(rejected_rules, list):
        errors.append("source_contract.rejected_rules must be a list")
        rejected_rules = []
    for idx, rule in enumerate(rejected_rules):
        required(rule, ["request_id", "source_id", "rule_id", "reason_code", "affected_field"], f"source_contract.rejected_rules[{idx}]", errors)

    claim = data.get("claim_contract")
    required(claim, ["effect_status", "comparison_scope", "claim_level", "claim_template_id", "comparison_evidence"], "claim_contract", errors)
    if isinstance(claim, dict):
        allowed_claim_keys = {"effect_status", "comparison_scope", "claim_level", "claim_template_id", "comparison_evidence"}
        if set(claim) != allowed_claim_keys:
            errors.append("claim_contract must use the closed claim schema; free effect claims are forbidden")
        status = claim.get("effect_status")
        if status not in CLAIM_STATUSES:
            errors.append(f"unsupported effect_status: {status}")
        elif (claim.get("comparison_scope"), claim.get("claim_level"), claim.get("claim_template_id")) != CLAIM_TEMPLATES[status]:
            errors.append("claim_contract does not match the closed claim template")
        evidence = claim.get("comparison_evidence")
        if not isinstance(evidence, dict):
            errors.append("claim_contract.comparison_evidence must be a structured object")
        elif status == "RELEASE_CANDIDATE":
            if evidence != {"scope": "STATIC_VALIDATION_ONLY", "self_test_suite": "PRISM-SELFTEST-01", "same_platform_abc": False}:
                errors.append("RELEASE_CANDIDATE evidence must be the closed static-validation receipt")
        elif status == "TESTED":
            required(evidence, ["platform_model", "abc_case_ids", "blind_review_id", "failure_ledger_id", "regression_id"], "claim_contract.comparison_evidence", errors)
            evidence_registry = data.get("evidence_registry")
            if not isinstance(evidence_registry, dict):
                errors.append("TESTED claim requires evidence_registry")
            else:
                case_ids = evidence.get("abc_case_ids", []) or []
                evidence_ids = list(case_ids) + [evidence.get("blind_review_id"), evidence.get("failure_ledger_id"), evidence.get("regression_id")]
                if not isinstance(case_ids, list) or len(set(map(str, case_ids))) < 3:
                    errors.append("TESTED claim requires at least three distinct A/B/C case IDs")
                for evidence_id in evidence_ids:
                    if str(evidence_id) not in evidence_registry:
                        errors.append(f"TESTED claim evidence is not registered: {evidence_id}")
                expected: dict[str, str] = {}
                for case_id in case_ids if isinstance(case_ids, list) else []:
                    expected[str(case_id)] = EVIDENCE_ROLE_TYPES["ABC_CASE"]
                expected[str(evidence.get("blind_review_id"))] = EVIDENCE_ROLE_TYPES["BLIND_REVIEW"]
                expected[str(evidence.get("failure_ledger_id"))] = EVIDENCE_ROLE_TYPES["FAILURE_LEDGER"]
                expected[str(evidence.get("regression_id"))] = EVIDENCE_ROLE_TYPES["REGRESSION_RUN"]
                abc_roles: set[str] = set()
                for evidence_id, expected_type in expected.items():
                    item = evidence_registry.get(evidence_id)
                    required(item, ["type", "role", "content_hash", "record_id"], f"evidence_registry.{evidence_id}", errors)
                    if not isinstance(item, dict):
                        continue
                    if item.get("type") != expected_type:
                        errors.append(f"evidence_registry.{evidence_id}: type does not match claim role")
                    content_hash = str(item.get("content_hash", ""))
                    if len(content_hash) != 64 or any(char not in "0123456789abcdef" for char in content_hash.lower()):
                        errors.append(f"evidence_registry.{evidence_id}: content_hash must be SHA-256 hex")
                    if expected_type == "A_B_C_CASE":
                        if item.get("role") not in {"A", "B", "C"}:
                            errors.append(f"evidence_registry.{evidence_id}: A/B/C case requires role A, B or C")
                        abc_roles.add(str(item.get("role")))
                if abc_roles != {"A", "B", "C"}:
                    errors.append("TESTED claim requires distinct A, B and C evidence roles")

    load = data.get("load_plan")
    required(load, ["primary_narrative", "medium_profile", "active_support", "composition_mechanisms_per_shot_max"], "load_plan", errors)
    if isinstance(load, dict):
        if load.get("primary_narrative") != "CREATIVE_TO_NARRATIVE":
            errors.append("load_plan.primary_narrative must be CREATIVE_TO_NARRATIVE")
        support = load.get("active_support", [])
        if not isinstance(support, list) or len(support) > 4:
            errors.append("load_plan.active_support must contain at most 4 modules")
            support = []
        elif len(support) != len(set(map(str, support))):
            errors.append("load_plan.active_support contains duplicates")
        for module in support:
            module_id = str(module).upper()
            if module_id not in ALLOWED_SUPPORT_MODULES:
                errors.append(f"unsupported active support module: {module}")
                continue
            for field, expected_owner in SUPPORT_OWNER_REQUIREMENTS.get(module_id, {}).items():
                if owners.get(field) != expected_owner:
                    errors.append(f"active support {module_id} is not bound to owner field {field}")
        max_mech = load.get("composition_mechanisms_per_shot_max")
        if not isinstance(max_mech, int) or max_mech > 3 or max_mech < 1:
            errors.append("load_plan.composition_mechanisms_per_shot_max must be 1..3")

    request = data.get("request_contract")
    if not isinstance(request, dict):
        errors.append("request_contract must be an object")
        request = {}
    for key in ("creative_or_asset_locks", "method_requests", "rejected_method_requests"):
        if key not in request or not isinstance(request.get(key), list):
            errors.append(f"request_contract.{key} must be a list")
    lock_ids: set[str] = set()
    for idx, lock in enumerate(request.get("creative_or_asset_locks", []) or []):
        label = f"request_contract.creative_or_asset_locks[{idx}]"
        required(lock, ["lock_id", "type", "source_id", "target_field", "raw_text"], label, errors)
        if isinstance(lock, dict):
            if lock.get("type") not in {"CREATIVE", "ASSET", "PRODUCTION"}:
                errors.append(f"{label}: unsupported lock type")
            if method_like(lock.get("raw_text")):
                errors.append("method request misclassified as CREATIVE_OR_ASSET_LOCK")
            target_field = str(lock.get("target_field", ""))
            raw_upper = str(lock.get("raw_text", "")).upper()
            if any(token in raw_upper for token in ("FEIRAN", "斐然", "SHANYIN", "山音", "MIRROR", "镜律")):
                errors.append("named source methodology cannot be classified as a Creative/asset/production lock")
            if any(token in target_field.lower() for token in ("method", "workflow", "rule", "director_system", "方法", "流程", "规则")):
                errors.append(f"{label}: method/workflow target cannot enter a Creative or asset lock")
            valid_prefixes = {
                "ASSET": ("project.identity", "project.wardrobe", "project.hand_prop", "project.asset", "assets."),
                "CREATIVE": ("story.", "character.", "world.", "narrative."),
                "PRODUCTION": ("project.duration", "project.budget", "project.platform", "project.location", "project.safety"),
            }
            if lock.get("type") in valid_prefixes and not target_field.startswith(valid_prefixes[lock.get("type")]):
                errors.append(f"{label}: target_field is incompatible with structured lock type")
            lock_id = str(lock.get("lock_id", ""))
            if lock_id in lock_ids:
                errors.append(f"duplicate request/lock id: {lock_id}")
            lock_ids.add(lock_id)
    method_ids: set[str] = set()
    shanyin_request_ids: set[str] = set()
    for idx, method in enumerate(request.get("method_requests", []) or []):
        label = f"request_contract.method_requests[{idx}]"
        required(method, ["request_id", "type", "source_id", "method_id", "raw_text"], label, errors)
        if isinstance(method, dict):
            if method.get("type") != "METHOD":
                errors.append(f"{label}: type must be METHOD")
            request_id = str(method.get("request_id", ""))
            if request_id in method_ids | lock_ids:
                errors.append(f"duplicate request/lock id: {request_id}")
            method_ids.add(request_id)
            method_id = str(method.get("method_id", ""))
            catalog_source = METHOD_CATALOG.get(method_id)
            if catalog_source is None:
                errors.append(f"{label}: method_id is not in the closed method catalog")
            elif normalized_source(method.get("source_id")) != catalog_source:
                errors.append(f"{label}: source_id contradicts the closed method catalog")
            if catalog_source == "SHANYIN":
                shanyin_request_ids.add(request_id)
    rejected_ids: set[str] = set()
    for idx, rejected in enumerate(request.get("rejected_method_requests", []) or []):
        label = f"request_contract.rejected_method_requests[{idx}]"
        required(rejected, ["request_id", "source_id", "method_id", "reason_code"], label, errors)
        if isinstance(rejected, dict):
            rid = str(rejected.get("request_id", ""))
            rejected_ids.add(rid)
            if rid not in method_ids:
                errors.append(f"{label}: request_id does not resolve to method_requests")
            else:
                original = next((item for item in request.get("method_requests", []) or [] if isinstance(item, dict) and str(item.get("request_id")) == rid), {})
                if rejected.get("source_id") != original.get("source_id") or rejected.get("method_id") != original.get("method_id"):
                    errors.append(f"{label}: rejected method source/method must match the original request")
            if rejected.get("reason_code") not in METHOD_REJECTION_REASONS:
                errors.append(f"{label}: unsupported rejection reason_code")
    notice = request.get("method_deviation_notice")
    required(notice, ["required", "emitted", "template_id", "notice_id", "notice_text"], "request_contract.method_deviation_notice", errors)
    unavailable_shanyin_ids = shanyin_request_ids if shanyin_status == "SOURCE_BODY_MISSING" else set()
    needs_notice = bool(rejected_ids | unavailable_shanyin_ids)
    if isinstance(notice, dict):
        if "rejected_request_ids" not in notice or not isinstance(notice.get("rejected_request_ids"), list):
            errors.append("request_contract.method_deviation_notice.rejected_request_ids must be a list")
        if notice.get("required") is not needs_notice:
            errors.append("method deviation notice required flag contradicts rejected/unavailable methods")
        if needs_notice and notice.get("emitted") is not True:
            errors.append("required method deviation notice was not emitted")
        covered = set(map(str, notice.get("rejected_request_ids", []) or []))
        if covered != rejected_ids | unavailable_shanyin_ids:
            errors.append("method deviation notice must cover every rejected or unavailable request ID")
        if needs_notice and (notice.get("template_id") != NOTICE_TEMPLATE_ID or notice.get("notice_text") != NOTICE_TEMPLATE_TEXT):
            errors.append("method deviation notice must use the closed missing-source fallback template")
        if not needs_notice and (notice.get("emitted") is not False or notice.get("template_id") != "NONE" or notice.get("notice_id") != "NONE" or notice.get("notice_text") != "NONE"):
            errors.append("available methods must use the closed no-deviation notice state")
    if isinstance(receipt, dict) and receipt.get("requested") is not bool(shanyin_request_ids):
        errors.append("ShanYin receipt.requested must match structured ShanYin method requests")

    rejected_rule_request_ids = {str(item.get("request_id")) for item in rejected_rules if isinstance(item, dict)}
    if not rejected_ids.issubset(rejected_rule_request_ids):
        errors.append("source_contract.rejected_rules must cover rejected method request IDs")

    receipts = data.get("layer_receipts")
    decision_registry = data.get("decision_registry")
    if not isinstance(decision_registry, dict) or not decision_registry:
        errors.append("decision_registry must be a non-empty object")
        decision_registry = {}
    else:
        for decision_id, decision in decision_registry.items():
            required(decision, ["owner", "status", "decision_hash"], f"decision_registry.{decision_id}", errors)
            if isinstance(decision, dict) and (decision.get("owner") != "CREATIVE_TO_NARRATIVE" or decision.get("status") != "APPROVED"):
                errors.append(f"decision_registry.{decision_id}: only Creative APPROVED decisions can authorize director compilation")
    if not isinstance(receipts, list) or not receipts:
        errors.append("layer_receipts must be a non-empty list")
    else:
        known_layers = {
            str(source.get("source_ir_id", "")): ("NARRATIVE_IR", str(source.get("source_ir_version", "")), "VALIDATED"),
            str(source.get("screenplay_layer_id", "")): ("SCREENPLAY", str(source.get("screenplay_version", "")), "VALIDATED"),
        }
        seen_receipt_ids: set[str] = set()
        for index, layer_receipt in enumerate(receipts):
            label = f"layer_receipts[{index}]"
            if not isinstance(layer_receipt, dict):
                errors.append(f"{label}: must be an object")
                continue
            for key in ("layer_type", "layer_id", "status", "source_layer_id", "source_version", "output_version", "preserved_truth_ids", "transformed_field_ids", "proposed_story_changes", "creative_decision_id"):
                if key not in layer_receipt:
                    errors.append(f"{label}: missing {key}")
            layer_type = str(layer_receipt.get("layer_type", ""))
            layer_id = str(layer_receipt.get("layer_id", ""))
            source_id = str(layer_receipt.get("source_layer_id", ""))
            status = str(layer_receipt.get("status", ""))
            if layer_type not in DIRECTOR_LAYER_ORDER:
                errors.append(f"{label}: unsupported director output layer_type")
            if layer_id in seen_receipt_ids or layer_id in known_layers:
                errors.append(f"{label}: duplicate layer_id")
            seen_receipt_ids.add(layer_id)
            if status not in {"CREATED", "VALIDATED", "REJECTED", "PENDING_CREATIVE_REVIEW"}:
                errors.append(f"{label}: unsupported status")
            if source_id not in known_layers:
                errors.append(f"{label}: source_layer_id does not reference a known source layer")
            else:
                source_type, source_version, source_status = known_layers[source_id]
                if source_status != "VALIDATED":
                    errors.append(f"{label}: upstream layer must be VALIDATED")
                if str(layer_receipt.get("source_version")) != source_version:
                    errors.append(f"{label}: source_version mismatch")
                source_order = 0 if source_type == "NARRATIVE_IR" else DIRECTOR_LAYER_ORDER.get(source_type)
                if layer_type in DIRECTOR_LAYER_ORDER and source_order is not None and DIRECTOR_LAYER_ORDER[layer_type] != source_order + 1:
                    errors.append(f"{label}: layer chain must advance exactly one compilation layer")
            if layer_receipt.get("proposed_story_changes") and status != "PENDING_CREATIVE_REVIEW":
                errors.append(f"{label}: proposed story changes require PENDING_CREATIVE_REVIEW")
            if status != "VALIDATED" and data.get("scenes"):
                errors.append(f"{label}: non-validated layer blocks formal director scene delivery")
            if status == "VALIDATED":
                for key in ("layer_id", "output_version", "creative_decision_id", "preserved_truth_ids", "transformed_field_ids"):
                    if layer_receipt.get(key) in (None, "", [], {}):
                        errors.append(f"{label}: VALIDATED receipt requires non-empty {key}")
                if str(layer_receipt.get("creative_decision_id", "")) not in decision_registry:
                    errors.append(f"{label}: creative_decision_id does not resolve to decision_registry")
                if str(source.get("frozen_story_core_id", "")) not in set(map(str, layer_receipt.get("preserved_truth_ids", []) or [])):
                    errors.append(f"{label}: director receipt must preserve frozen_story_core_id")
                runtime = data.get("runtime_context", {}) if isinstance(data.get("runtime_context"), dict) else {}
                if runtime.get("validation_mode") == "FORMAL_DELIVERY":
                    roles = set(map(str, layer_receipt.get("preserved_truth_roles", []) or []))
                    required_roles = {"CORE_ID", "CLIMAX_CHOICE", "SCENE_OUTCOME", "INFORMATION_PERMISSIONS"}
                    if not required_roles.issubset(roles):
                        errors.append(f"{label}: formal director receipt lacks required preserved truth roles")
            known_layers[layer_id] = (layer_type, str(layer_receipt.get("output_version", "")), status)


def validate(data: dict[str, Any], narrative_provided: bool = False) -> tuple[list[str], list[str]]:
    errors: list[str] = []
    warnings: list[str] = []
    validate_authority(data, errors, warnings)
    runtime = data.get("runtime_context", {}) if isinstance(data.get("runtime_context"), dict) else {}
    if runtime.get("validation_mode") == "FORMAL_DELIVERY" and not narrative_provided:
        errors.append("FORMAL_DELIVERY requires --narrative-ir cross-layer validation")
    project = data.get("project")
    required(project, ["project_id", "mode", "delivery_profile", "duration", "aspect_ratio", "wardrobe_policy", "frozen_assets", "asset_registry", "frozen_asset_bindings"], "project", errors)
    if not isinstance(project, dict):
        return errors, warnings
    unknown_project_keys = set(project) - PROJECT_KEYS
    if unknown_project_keys:
        errors.append(f"project uses unregistered fields: {sorted(unknown_project_keys)}")
    duration = project.get("duration")
    if not numeric(duration) or duration <= 0:
        errors.append("project.duration must be a positive finite number")
    atomic = project.get("delivery_profile") == "ATOMIC_VIDEO_PACKAGE"
    composition_max = data.get("load_plan", {}).get("composition_mechanisms_per_shot_max", 3) if isinstance(data.get("load_plan"), dict) else 3
    authorized_changes = project.get("authorized_changes", []) or []
    if not isinstance(authorized_changes, list):
        errors.append("project.authorized_changes must be a list")
        authorized_changes = []
    asset_registry = project.get("asset_registry", {})
    if not isinstance(asset_registry, dict) or not asset_registry:
        errors.append("project.asset_registry must be a non-empty object")
        asset_registry = {}
    for frozen in project.get("frozen_assets", []) or []:
        if str(frozen) not in asset_registry:
            errors.append(f"frozen asset is not registered: {frozen}")
    frozen_bindings = project.get("frozen_asset_bindings", {})
    required(frozen_bindings, ["identity", "wardrobe", "hand_props"], "project.frozen_asset_bindings", errors)
    production_constraints = project.get("production_constraints")
    if not isinstance(production_constraints, list) or not production_constraints:
        errors.append("project.production_constraints must be a non-empty list of registered constraint IDs")
    else:
        for constraint_id in production_constraints:
            if str(constraint_id) not in PRODUCTION_CONSTRAINT_IDS:
                errors.append(f"unregistered production constraint ID: {constraint_id}")
    if isinstance(frozen_bindings, dict):
        for prop_id in frozen_bindings.get("hand_props", []) or []:
            if str(prop_id) not in asset_registry:
                errors.append(f"frozen hand-prop identity is not registered: {prop_id}")
    action_registry = data.get("action_registry")
    if not isinstance(action_registry, dict) or not action_registry:
        errors.append("action_registry must be a non-empty ID-keyed object")
        action_registry = {}
    else:
        for action_id, action_spec in action_registry.items():
            required(action_spec, ["role", "atomic", "contact_policy"], f"action_registry.{action_id}", errors)
            if isinstance(action_spec, dict):
                if action_spec.get("role") not in {"MAIN", "REACTION"}:
                    errors.append(f"action_registry.{action_id}: unsupported role")
                if action_spec.get("atomic") is not True:
                    errors.append(f"action_registry.{action_id}: atomic must be true")
                if action_spec.get("contact_policy") not in {"REQUIRED", "FORBIDDEN", "OPTIONAL"}:
                    errors.append(f"action_registry.{action_id}: unsupported contact_policy")
    reaction_target_registry = data.get("reaction_target_registry")
    if not isinstance(reaction_target_registry, dict) or not reaction_target_registry:
        errors.append("reaction_target_registry must be a non-empty ID-keyed object")
        reaction_target_registry = {}
    else:
        for target_id, target_spec in reaction_target_registry.items():
            required(target_spec, ["type", "source"], f"reaction_target_registry.{target_id}", errors)
            if isinstance(target_spec, dict) and target_spec.get("type") not in {"PERCEPTUAL_CUE", "AUDIENCE_AXIS", "ENVIRONMENT_CUE", "SPATIAL_CUE"}:
                errors.append(f"reaction_target_registry.{target_id}: unsupported target type")

    av_policy = data.get("av_policy")
    required(
        av_policy,
        ["policy_id", "subtitles", "captions_or_text_overlay", "background_music", "diegetic_dialogue", "diegetic_visible_text", "cinematic_sfx", "silence", "dialogue_language"],
        "av_policy",
        errors,
    )
    if isinstance(av_policy, dict):
        if av_policy.get("subtitles") not in {"FORBIDDEN", "ALLOWED"}:
            errors.append("av_policy.subtitles must be FORBIDDEN or ALLOWED")
        if av_policy.get("captions_or_text_overlay") not in {"FORBIDDEN", "ALLOWED"}:
            errors.append("av_policy.captions_or_text_overlay must be FORBIDDEN or ALLOWED")
        if av_policy.get("background_music") not in {"FORBIDDEN", "ALLOWED", "DIEGETIC_ONLY"}:
            errors.append("av_policy.background_music uses an unsupported value")
        if av_policy.get("cinematic_sfx") not in {"REQUIRED", "OPTIONAL"}:
            errors.append("av_policy.cinematic_sfx must be REQUIRED or OPTIONAL")
        if av_policy.get("silence") not in {"DESIGNED", "OPTIONAL"}:
            errors.append("av_policy.silence must be DESIGNED or OPTIONAL")

    style = data.get("style_contract")
    required(
        style,
        ["style_contract_id", "profile_id", "scope", "visual_thesis", "medium", "identity_lock", "material_logic", "motion_logic", "background_logic", "finish_target", "continuity_locks", "forbidden", "clean_motif_id"],
        "style_contract",
        errors,
    )
    if isinstance(style, dict):
        if style.get("scope") != "PROJECT":
            errors.append("style_contract.scope must be PROJECT")
        if style.get("finish_target") != "4K_CINEMATIC_FINISH":
            errors.append("style_contract.finish_target must express a target, not a native-output guarantee")
        style_text = json.dumps(style, ensure_ascii=False).lower()
        named_tokens = {"nolan", "miyazaki", "wong kar-wai", "spielberg", "诺兰", "宫崎骏", "王家卫", "张艺谋", "斯皮尔伯格"}
        if any(token in style_text for token in named_tokens):
            errors.append("style_contract must use anonymous mechanisms instead of named-director imitation")
    else:
        style = {}

    sound_registry = data.get("sound_registry")
    if not isinstance(sound_registry, dict) or not sound_registry:
        errors.append("sound_registry must be a non-empty ID-keyed object")
        sound_registry = {}
    else:
        for sound_id, sound in sound_registry.items():
            label = f"sound_registry.{sound_id}"
            required(sound, ["shot_ids", "source_entity_or_world_event", "physical_or_world_trigger", "spatial_origin_xyz_or_zone", "phase", "sync_to_action_or_image_evidence_id", "dramatic_job", "tail_handoff", "music_classification"], label, errors)
            if isinstance(sound, dict):
                if sound.get("phase") not in SOUND_PHASES:
                    errors.append(f"{label}: unsupported sound phase")
                if sound.get("music_classification") not in SOUND_CLASSES:
                    errors.append(f"{label}: unsupported music classification")
                if isinstance(av_policy, dict) and av_policy.get("background_music") == "FORBIDDEN" and sound.get("music_classification") == "SCORE":
                    errors.append(f"{label}: score contradicts background_music FORBIDDEN")
        if isinstance(av_policy, dict) and av_policy.get("cinematic_sfx") == "REQUIRED" and not any(
            isinstance(item, dict) and item.get("music_classification") == "NOT_MUSIC" for item in sound_registry.values()
        ):
            errors.append("cinematic_sfx REQUIRED needs at least one non-music sound event")

    if isinstance(av_policy, dict):
        if av_policy.get("background_music") == "FORBIDDEN" and any(value not in (None, "", False, "FORBIDDEN", "NONE", []) for value in recursive_key_values(data.get("scenes"), {"bgm", "background_music", "score"})):
            errors.append("scene-level music contradicts background_music FORBIDDEN")
        if av_policy.get("subtitles") == "FORBIDDEN" and any(value not in (None, "", False, "FORBIDDEN", "NONE", []) for value in recursive_key_values(data.get("scenes"), {"subtitle", "subtitles"})):
            errors.append("scene-level subtitles contradict subtitles FORBIDDEN")
        if av_policy.get("captions_or_text_overlay") == "FORBIDDEN" and any(value not in (None, "", False, "FORBIDDEN", "NONE", []) for value in recursive_key_values(data.get("scenes"), {"caption", "captions", "text_overlay"})):
            errors.append("scene-level text overlay contradicts captions_or_text_overlay FORBIDDEN")

    performance_units = data.get("performance_units")
    if not isinstance(performance_units, dict) or not performance_units:
        errors.append("performance_units must be a non-empty ID-keyed object")
        performance_units = {}
    else:
        for unit_id, unit in performance_units.items():
            label = f"performance_units.{unit_id}"
            required(
                unit,
                ["source_scene_id", "source_beat_id", "shot_ids", "actor_id", "stimulus_or_trigger", "scene_objective", "speech_action", "power_position", "arousal_level", "response_seeking", "voice_contract", "dominant_visible_channel", "support_micro_action", "gaze_target", "body_anchor", "prop_action_id", "counterpart_reaction_id", "residue", "rendered_evidence", "intended_inference", "alternative_interpretations", "evidence_status", "forbidden_explanations"],
                label,
                errors,
            )
            if not isinstance(unit, dict):
                continue
            required(unit.get("voice_contract"), ["pace", "loudness", "pressure", "terminal_contour", "pause_or_breath"], f"{label}.voice_contract", errors)
            if unit.get("response_seeking") not in {"LOW", "MEDIUM", "HIGH"}:
                errors.append(f"{label}: unsupported response_seeking")
            if unit.get("evidence_status") not in {"HYPOTHESIZED", "CANDIDATE", "TESTED"}:
                errors.append(f"{label}: unsupported evidence_status")
            rendered = str(unit.get("rendered_evidence", ""))
            if any(token in rendered for token in ("内心", "心想", "觉得自己", "仿佛恩赐", "显得自信", "充满自信")):
                errors.append(f"{label}: rendered evidence contains mind-reading or explanatory acting")
            if str(unit.get("prop_action_id")) not in action_registry:
                errors.append(f"{label}: prop_action_id must resolve to action_registry")
            if str(unit.get("counterpart_reaction_id")) not in action_registry:
                errors.append(f"{label}: counterpart_reaction_id must resolve to action_registry")

    scenes = data.get("scenes")
    if not isinstance(scenes, list) or not scenes:
        errors.append("scenes must be a non-empty list")
        return errors, warnings

    seen_scene: set[str] = set()
    seen_source_scene: set[str] = set()
    seen_shot: set[str] = set()
    shot_source_beats: dict[str, str] = {}
    shot_scene_entities: dict[str, set[str]] = {}
    timeline: list[tuple[float, float, str]] = []
    scene_windows: list[tuple[float, float, str]] = []
    transition_ids: dict[str, int] = {}
    flat_shots: list[tuple[dict[str, Any], dict[str, Any]]] = []
    composition_catalog_used = False

    for s_idx, scene in enumerate(scenes):
        sid = str(scene.get("scene_id") or f"scene[{s_idx}]")
        required(scene, ["scene_id", "source_scene_id", "mode", "t_in", "t_out", "duration", "narrative_or_rhythm_function", "world_frame", "coordinate_bounds", "entity_registry", "entrance_state", "exit_state", "shots"], sid, errors)
        if sid in seen_scene:
            errors.append(f"duplicate scene_id: {sid}")
        seen_scene.add(sid)
        source_sid = str(scene.get("source_scene_id", ""))
        if source_sid in seen_source_scene:
            errors.append(f"duplicate source_scene_id in director scenes: {source_sid}")
        seen_source_scene.add(source_sid)
        st, et, sd = scene.get("t_in"), scene.get("t_out"), scene.get("duration")
        if not all(numeric(v) for v in (st, et, sd)) or et <= st or abs((et - st) - sd) > 1e-3:
            errors.append(f"{sid}: invalid t_in/t_out/duration")
        else:
            scene_windows.append((float(st), float(et), sid))
        world = scene.get("world_frame")
        required(world, ["origin", "X", "Y", "Z", "unit", "handedness"], f"{sid}.world_frame", errors)
        bounds = scene.get("coordinate_bounds")
        required(bounds, ["min", "max"], f"{sid}.coordinate_bounds", errors)
        if isinstance(bounds, dict) and (not coord(bounds.get("min")) or not coord(bounds.get("max"))):
            errors.append(f"{sid}.coordinate_bounds: min/max must be numeric XYZ")
        entity_registry = scene.get("entity_registry")
        if not isinstance(entity_registry, dict) or not entity_registry:
            errors.append(f"{sid}.entity_registry must be a non-empty object")
            entity_ids: set[str] = set()
        else:
            entity_ids = {str(key) for key in entity_registry}
            for entity_id, entity_spec in entity_registry.items():
                if not isinstance(entity_spec, dict) or not entity_spec.get("type"):
                    errors.append(f"{sid}.entity_registry.{entity_id}: missing entity type")
        if isinstance(frozen_bindings, dict):
            for prop_id in frozen_bindings.get("hand_props", []) or []:
                if str(prop_id) not in entity_ids:
                    errors.append(f"{sid}: frozen prop identity missing from scene asset registry: {prop_id}")
        zones = {str(item.get("id")) for item in scene.get("zones", []) if isinstance(item, dict) and item.get("id")}
        support_ids = {str(item.get("id")) for item in scene.get("support_surfaces", []) if isinstance(item, dict) and item.get("id")}

        shots = scene.get("shots")
        if not isinstance(shots, list) or not shots:
            errors.append(f"{sid}: shots must be non-empty")
            continue
        for h_idx, shot in enumerate(shots):
            if not isinstance(shot, dict):
                errors.append(f"{sid}.shot[{h_idx}]: must be an object")
                continue
            hid = str(shot.get("shot_id") or f"{sid}.shot[{h_idx}]")
            required(shot, ["shot_id", "scene_id", "source_scene_id", "source_beat_id", "generation_segment_id", "state_delta_id", "t_in", "t_out", "logic_chain", "action_chain", "image_chain", "xyz", "assets", "transition"], hid, errors)
            if hid in seen_shot:
                errors.append(f"duplicate shot_id: {hid}")
            seen_shot.add(hid)
            shot_source_beats[hid] = str(shot.get("source_beat_id", ""))
            shot_scene_entities[hid] = set(entity_ids)
            if shot.get("scene_id") != sid:
                errors.append(f"{hid}: scene_id does not match parent scene {sid}")
            if shot.get("source_scene_id") != scene.get("source_scene_id"):
                errors.append(f"{hid}: source_scene_id does not match parent source scene")
            t_in, t_out = shot.get("t_in"), shot.get("t_out")
            if not numeric(t_in) or not numeric(t_out) or t_out <= t_in:
                errors.append(f"{hid}: invalid t_in/t_out")
            else:
                timeline.append((float(t_in), float(t_out), hid))
                if numeric(st) and numeric(et) and (t_in < st - 1e-6 or t_out > et + 1e-6):
                    errors.append(f"{hid}: time outside parent scene")

            logic, action, image = shot.get("logic_chain"), shot.get("action_chain"), shot.get("image_chain")
            edges: list[Any] = []
            required(logic, ["beat_id", "state_delta_id", "goal_or_pressure", "trigger", "consequence", "state_delta", "next_need"], f"{hid}.logic_chain", errors)
            required(action, ["beat_id", "state_delta_id", "primary_actor", "participants", "delta_refs", "state_in", "delta_state_in", "preparation", "main_action", "recovery", "residue", "delta_state_out", "state_out"], f"{hid}.action_chain", errors)
            required(image, ["beat_id", "state_delta_id", "shot_function", "visual_center", "eye_path", "composition_mechanisms", "observable_delta_refs", "evidence_registry", "observable_delta", "end_composition"], f"{hid}.image_chain", errors)
            if all(isinstance(block, dict) for block in (logic, action, image)):
                beat_ids = {block.get("beat_id") for block in (logic, action, image)}
                delta_ids = {block.get("state_delta_id") for block in (logic, action, image)} | {shot.get("state_delta_id")}
                if len(beat_ids) != 1 or None in beat_ids:
                    errors.append(f"{hid}: L/A/I beat_id values must match")
                if len(delta_ids) != 1 or None in delta_ids:
                    errors.append(f"{hid}: L/A/I/shot state_delta_id values must match")
                delta = logic.get("state_delta")
                delta_keys = state_delta_keys(delta)
                if not delta_keys:
                    errors.append(f"{hid}: logic state_delta must use before/after objects with a material change")
                action_refs = set(map(str, action.get("delta_refs", []) or []))
                image_refs = set(map(str, image.get("observable_delta_refs", []) or []))
                if action_refs != delta_keys or image_refs != delta_keys:
                    errors.append(f"{hid}: action/image delta refs must cover the same logic state_delta keys")
                evidence_registry = image.get("evidence_registry", {})
                if not isinstance(evidence_registry, dict):
                    errors.append(f"{hid}: image evidence_registry must be an ID-keyed object")
                    evidence_registry = {}
                for delta_key in delta_keys:
                    item = delta.get(delta_key, {})
                    required(item, ["before", "after", "action_state_path", "image_evidence_ids"], f"{hid}.logic_chain.state_delta.{delta_key}", errors)
                    if not isinstance(item, dict):
                        continue
                    state_path = str(item.get("action_state_path", ""))
                    if get_path(action.get("delta_state_in", {}), state_path) != item.get("before") or get_path(action.get("delta_state_out", {}), state_path) != item.get("after"):
                        errors.append(f"{hid}: action state path does not realize logic delta {delta_key}")
                    evidence_ids = item.get("image_evidence_ids", []) or []
                    if not isinstance(evidence_ids, list) or not evidence_ids:
                        errors.append(f"{hid}: logic delta {delta_key} requires image evidence IDs")
                        continue
                    for evidence_id in evidence_ids:
                        evidence = evidence_registry.get(str(evidence_id))
                        if not isinstance(evidence, dict):
                            errors.append(f"{hid}: image evidence ID does not resolve: {evidence_id}")
                            continue
                        required(evidence, ["field", "evidence_type", "description"], f"{hid}.image_chain.evidence_registry.{evidence_id}", errors)
                        if evidence.get("field") != delta_key:
                            errors.append(f"{hid}: image evidence {evidence_id} is bound to the wrong delta field")
                        if evidence.get("evidence_type") not in EVIDENCE_TYPES:
                            errors.append(f"{hid}: unsupported image evidence type for {evidence_id}")
                observable_text = str(image.get("observable_delta", "")).strip().lower()
                if not observable_text or observable_text in {"nothing changes", "no change", "unchanged", "无变化", "没有变化"}:
                    errors.append(f"{hid}: image observable_delta contradicts material state change")

            if isinstance(action, dict):
                if action.get("primary_actor") not in entity_ids:
                    errors.append(f"{hid}: action primary_actor is not a registered scene entity")
                for participant in action.get("participants", []) or []:
                    if entity_base(participant) not in entity_ids:
                        errors.append(f"{hid}: unregistered action participant {participant}")
                main_action = action.get("main_action")
                required(main_action, ["action_id", "verb", "target", "start_state", "end_state"], f"{hid}.action_chain.main_action", errors)
                if atomic and isinstance(main_action, dict) and isinstance(main_action.get("sub_actions"), list) and len(main_action["sub_actions"]) > 1:
                    errors.append(f"{hid}: atomic segment contains multiple main sub-actions")
                if isinstance(main_action, dict):
                    action_id = str(main_action.get("action_id", ""))
                    action_spec = action_registry.get(action_id)
                    if not isinstance(action_spec, dict) or action_spec.get("role") != "MAIN":
                        errors.append(f"{hid}: main action_id is not registered as MAIN")
                    verb = str(main_action.get("verb", ""))
                    if any(token in verb.lower() for token in ("-", "/", ",", "+", " and ", " then ", "并", "再", "然后")):
                        errors.append(f"{hid}: atomic main_action verb hides multiple actions")
                    target = str(main_action.get("target", ""))
                    valid_action_targets = entity_ids | zones | support_ids
                    if target not in valid_action_targets:
                        errors.append(f"{hid}: main_action.target does not resolve to an entity, zone or support")
                    target_type = None
                    if target in entity_ids and isinstance(entity_registry.get(target), dict):
                        target_type = str(entity_registry[target].get("type"))
                    elif target in support_ids:
                        target_type = "rigid-environment"
                    derived_contact = target_type in ENTITY_TARGET_TYPES_REQUIRING_CONTACT
                    declared_contact = main_action.get("requires_contact")
                    if not isinstance(declared_contact, bool):
                        errors.append(f"{hid}: main_action.requires_contact must be boolean")
                    elif declared_contact != derived_contact:
                        errors.append(f"{hid}: main_action.requires_contact contradicts target semantics")
                    if isinstance(action_spec, dict):
                        expected_policy = "REQUIRED" if derived_contact else "FORBIDDEN"
                        if action_spec.get("contact_policy") != expected_policy:
                            errors.append(f"{hid}: action_registry contact_policy contradicts target semantics")
                reaction = action.get("reaction_action")
                if reaction not in (None, {}, "") and not isinstance(reaction, dict):
                    errors.append(f"{hid}: reaction_action must be one object or empty")
                elif isinstance(reaction, dict) and reaction:
                    required(reaction, ["action_id", "verb", "target", "start_state", "end_state"], f"{hid}.action_chain.reaction_action", errors)
                    reaction_spec = action_registry.get(str(reaction.get("action_id", "")))
                    if not isinstance(reaction_spec, dict) or reaction_spec.get("role") != "REACTION":
                        errors.append(f"{hid}: reaction action_id is not registered as REACTION")
                    reaction_verb = str(reaction.get("verb", ""))
                    if any(token in reaction_verb.lower() for token in ("-", "/", ",", "+", " and ", " then ", "并", "再", "然后")):
                        errors.append(f"{hid}: atomic reaction_action verb hides multiple actions")
                    reaction_target = str(reaction.get("target", ""))
                    if reaction_target not in entity_ids | zones | support_ids | set(reaction_target_registry):
                        errors.append(f"{hid}: reaction_action.target does not resolve to an entity, zone, support or registered cue")
                    if isinstance(reaction.get("sub_actions"), list) and len(reaction.get("sub_actions", [])) > 1:
                        errors.append(f"{hid}: atomic reaction_action contains multiple sub-actions")
                requires_contact = isinstance(main_action, dict) and main_action.get("requires_contact") is True
                edges = action.get("interaction_edges", []) or []
                if requires_contact and not edges:
                    errors.append(f"{hid}: contact action requires interaction_edges")
                if requires_contact and isinstance(main_action, dict) and edges and not any(entity_base(edge.get("target")) == str(main_action.get("target")) for edge in edges if isinstance(edge, dict)):
                    errors.append(f"{hid}: contact action has no interaction edge for its main target")
                for e_idx, edge in enumerate(edges):
                    required(edge, ["edge_id", "spatial_contact_id", "actor", "actor_part", "target", "target_contact_part", "precondition", "approach_path", "contact_part", "target_response", "environment_feedback", "recovery", "residue", "postcondition"], f"{hid}.interaction_edges[{e_idx}]", errors)
                    if isinstance(edge, dict):
                        if entity_base(edge.get("actor")) not in entity_ids:
                            errors.append(f"{hid}: interaction actor is not registered")
                        if entity_base(edge.get("target")) not in entity_ids and str(edge.get("target")) not in support_ids:
                            errors.append(f"{hid}: interaction target is not registered")
                if edges:
                    visible = image.get("visible_contact_ids", []) if isinstance(image, dict) else []
                    edge_ids = {edge.get("edge_id") for edge in edges if isinstance(edge, dict)}
                    spatial_ids = {edge.get("spatial_contact_id") for edge in edges if isinstance(edge, dict)}
                    if not (edge_ids | spatial_ids).issubset(set(visible or [])):
                        errors.append(f"{hid}: every interaction edge must be visible or explicitly represented")

            if isinstance(image, dict):
                mechanisms = image.get("composition_mechanisms")
                if not isinstance(mechanisms, list) or not mechanisms:
                    errors.append(f"{hid}: composition_mechanisms must be a non-empty list")
                elif isinstance(composition_max, int) and len(mechanisms) > composition_max:
                    errors.append(f"{hid}: composition mechanisms exceed declared per-shot budget")
                else:
                    composition_catalog_used = True
                    categories: list[str] = []
                    for mechanism_id in mechanisms:
                        if str(mechanism_id) not in COMPOSITION_CATALOG:
                            errors.append(f"{hid}: unregistered composition mechanism {mechanism_id}")
                        else:
                            categories.append(COMPOSITION_CATALOG[str(mechanism_id)])
                    if len(categories) != len(set(categories)):
                        errors.append(f"{hid}: composition mechanisms repeat one functional category")

            xyz = shot.get("xyz")
            required(xyz, ["primary_actor", "entities_start", "entities_end", "actor_start", "actor_end", "camera_start", "camera_end", "camera_frame", "axis_relation", "screen_direction", "route", "support_surface", "contact_points", "collision_margin"], f"{hid}.xyz", errors)
            if isinstance(xyz, dict):
                if xyz.get("axis_relation") not in AXIS_RELATIONS:
                    errors.append(f"{hid}: unsupported axis_relation")
                if xyz.get("screen_direction") not in SCREEN_DIRECTIONS:
                    errors.append(f"{hid}: unsupported screen_direction")
                for key in ("actor_start", "actor_end", "camera_start", "camera_end"):
                    if not coord(xyz.get(key)):
                        errors.append(f"{hid}.xyz.{key}: must be three finite numbers")
                    elif not within_bounds(xyz.get(key), bounds):
                        errors.append(f"{hid}.xyz.{key}: outside scene coordinate bounds")
                if xyz.get("primary_actor") != action.get("primary_actor") if isinstance(action, dict) else True:
                    errors.append(f"{hid}: action and xyz primary_actor must match")
                starts, ends = xyz.get("entities_start"), xyz.get("entities_end")
                if not isinstance(starts, dict) or not isinstance(ends, dict) or not starts or not ends:
                    errors.append(f"{hid}: entities_start/end must be non-empty mappings")
                else:
                    if set(starts) != set(ends):
                        errors.append(f"{hid}: entities_start/end entity sets must match")
                    for entity_id, point in {**starts, **ends}.items():
                        if str(entity_id) not in entity_ids:
                            errors.append(f"{hid}: spatial entity is not registered: {entity_id}")
                        if not coord(point) or not within_bounds(point, bounds):
                            errors.append(f"{hid}: invalid or out-of-bounds entity coordinate: {entity_id}")
                    primary = str(xyz.get("primary_actor"))
                    if starts.get(primary) != xyz.get("actor_start") or ends.get(primary) != xyz.get("actor_end"):
                        errors.append(f"{hid}: actor_start/end must equal primary entity coordinates")
                camera_frame = xyz.get("camera_frame")
                required(camera_frame, ["screen_start_uvd", "screen_end_uvd", "uv_unit", "uv_domain", "projection_intent"], f"{hid}.xyz.camera_frame", errors)
                if isinstance(camera_frame, dict):
                    if camera_frame.get("uv_unit") not in UV_UNITS:
                        errors.append(f"{hid}: unsupported camera_frame.uv_unit")
                    for key in ("screen_start_uvd", "screen_end_uvd"):
                        if not coord(camera_frame.get(key)):
                            errors.append(f"{hid}.xyz.camera_frame.{key}: must be three finite numbers")
                        else:
                            u, v, depth = camera_frame[key]
                            domain = camera_frame.get("uv_domain")
                            if depth <= 0:
                                errors.append(f"{hid}.xyz.camera_frame.{key}: depth D must be positive")
                            if not isinstance(domain, list) or len(domain) != 2 or not all(numeric(item) for item in domain) or not domain[0] < domain[1]:
                                errors.append(f"{hid}.xyz.camera_frame.uv_domain: must be [min,max]")
                            elif not (domain[0] <= u <= domain[1] and domain[0] <= v <= domain[1]):
                                errors.append(f"{hid}.xyz.camera_frame.{key}: U/V outside declared domain")
                    start_uvd, end_uvd = camera_frame.get("screen_start_uvd"), camera_frame.get("screen_end_uvd")
                    if coord(start_uvd) and coord(end_uvd):
                        du = end_uvd[0] - start_uvd[0]
                        direction = str(xyz.get("screen_direction", "")).lower()
                        if ("left-to-right" in direction or "to-right" in direction or "left-to-center" in direction) and du <= 0:
                            errors.append(f"{hid}: screen_direction contradicts U movement")
                        if ("right-to-left" in direction or "to-left" in direction or "right-to-center" in direction) and du >= 0:
                            errors.append(f"{hid}: screen_direction contradicts U movement")
                if xyz.get("support_surface") not in support_ids:
                    errors.append(f"{hid}: unregistered support_surface {xyz.get('support_surface')}")
                route = xyz.get("route")
                if not isinstance(route, str) or not route:
                    errors.append(f"{hid}: route must be one registered zone ID")
                elif zones and route not in zones:
                    errors.append(f"{hid}: route references unregistered zone {route}")
                contacts = xyz.get("contact_points")
                if not isinstance(contacts, list) or not contacts:
                    errors.append(f"{hid}: contact_points must be a non-empty structured list")
                else:
                    contact_by_id: dict[str, dict[str, Any]] = {}
                    for c_idx, contact in enumerate(contacts):
                        required(contact, ["contact_id", "actor_entity", "actor_part", "target_entity", "target_part"], f"{hid}.xyz.contact_points[{c_idx}]", errors)
                        if isinstance(contact, dict):
                            contact_id = str(contact.get("contact_id", ""))
                            if contact_id in contact_by_id:
                                errors.append(f"{hid}: duplicate spatial contact_id {contact_id}")
                            contact_by_id[contact_id] = contact
                            valid_targets = entity_ids | support_ids
                            if entity_base(contact.get("actor_entity")) not in entity_ids:
                                errors.append(f"{hid}: contact actor entity is not registered")
                            if entity_base(contact.get("target_entity")) not in valid_targets:
                                errors.append(f"{hid}: contact target entity is not registered")
                    used_spatial_contact_ids: set[str] = set()
                    for edge in edges:
                        if not isinstance(edge, dict):
                            continue
                        spatial_contact_id = str(edge.get("spatial_contact_id", ""))
                        if spatial_contact_id in used_spatial_contact_ids:
                            errors.append(f"{hid}: interaction edges must map one-to-one to spatial contact IDs")
                        used_spatial_contact_ids.add(spatial_contact_id)
                        contact = contact_by_id.get(spatial_contact_id)
                        if not contact:
                            errors.append(f"{hid}: interaction edge spatial_contact_id does not resolve")
                            continue
                        if entity_base(edge.get("actor")) != entity_base(contact.get("actor_entity")):
                            errors.append(f"{hid}: interaction edge actor contradicts spatial contact")
                        if entity_base(edge.get("target")) != entity_base(contact.get("target_entity")):
                            errors.append(f"{hid}: interaction edge target contradicts spatial contact")
                        if normalized_body_part(edge.get("actor_part")) != normalized_body_part(contact.get("actor_part")):
                            errors.append(f"{hid}: interaction edge actor part contradicts spatial contact")
                        if normalized_body_part(edge.get("contact_part")) != normalized_body_part(contact.get("actor_part")):
                            errors.append(f"{hid}: interaction edge contact_part contradicts spatial contact actor part")
                        if normalized_body_part(edge.get("target_contact_part")) != normalized_body_part(contact.get("target_part")):
                            errors.append(f"{hid}: interaction edge target part contradicts spatial contact")
                margin = xyz.get("collision_margin")
                required(margin, ["status", "evidence"], f"{hid}.xyz.collision_margin", errors)
                if isinstance(margin, dict) and margin.get("status") not in {"CLEAR", "CONTACT_PLANNED", "HOLD"}:
                    errors.append(f"{hid}: unsupported collision margin status")
                if xyz.get("axis_relation") == "CROSS" and not xyz.get("axis_crossing_method"):
                    errors.append(f"{hid}: axis crossing requires axis_crossing_method")

            assets = shot.get("assets")
            required(assets, ["identity", "wardrobe", "hand_props", "softbody"], f"{hid}.assets", errors)
            if isinstance(assets, dict):
                if str(assets.get("identity")) not in asset_registry:
                    errors.append(f"{hid}: identity asset is not registered")
                if str(assets.get("wardrobe")) not in asset_registry:
                    errors.append(f"{hid}: wardrobe asset is not registered")
                if isinstance(frozen_bindings, dict):
                    if assets.get("identity") != frozen_bindings.get("identity"):
                        errors.append(f"{hid}: frozen identity binding was replaced")
                    if assets.get("wardrobe") != frozen_bindings.get("wardrobe"):
                        errors.append(f"{hid}: frozen wardrobe binding was replaced")
                occupied_slots: set[tuple[str, str]] = set()
                for p_idx, prop in enumerate(assets.get("hand_props", []) or []):
                    required(prop, ["prop_id", "owner", "hand", "grip", "contact", "orientation", "state_ref", "state_in", "state_out", "legal_exit"], f"{hid}.assets.hand_props[{p_idx}]", errors)
                    if isinstance(prop, dict):
                        if str(prop.get("prop_id")) not in asset_registry or str(prop.get("prop_id")) not in entity_ids:
                            errors.append(f"{hid}: hand prop is not registered as project and scene asset")
                        if str(prop.get("owner")) not in entity_ids:
                            errors.append(f"{hid}: prop owner is not a registered scene entity")
                        slot = (str(prop.get("owner")), str(prop.get("hand")))
                        if slot in occupied_slots and prop.get("shared_grip_contract") is not True:
                            errors.append(f"{hid}: multiple props occupy the same hand slot without shared_grip_contract")
                        occupied_slots.add(slot)
                        action_in = action.get("state_in", {}) if isinstance(action, dict) else {}
                        action_out = action.get("state_out", {}) if isinstance(action, dict) else {}
                        state_ref = str(prop.get("state_ref", ""))
                        if get_path(action_in, state_ref) != prop.get("state_in") or get_path(action_out, state_ref) != prop.get("state_out"):
                            errors.append(f"{hid}: action prop state contradicts PROP_STATE")
                for b_idx, body in enumerate(assets.get("softbody", []) or []):
                    required(body, ["softbody_id", "owner", "anchor", "wind_source", "wind_direction", "lag", "collision_body", "initial_motion", "residue", "settle_condition"], f"{hid}.assets.softbody[{b_idx}]", errors)
                    if isinstance(body, dict):
                        if str(body.get("softbody_id")) not in entity_ids:
                            errors.append(f"{hid}: softbody is not a registered scene entity")
                        if str(body.get("owner")) not in entity_ids or str(body.get("collision_body")) not in entity_ids:
                            errors.append(f"{hid}: softbody owner/collision body must resolve to scene entities")
                        if entity_base(body.get("anchor")) != str(body.get("owner")) or "." not in str(body.get("anchor", "")):
                            errors.append(f"{hid}: softbody anchor must resolve to owner.body_part")
                        source_event_ids = {
                            str(action.get("main_action", {}).get("action_id", "")) if isinstance(action, dict) and isinstance(action.get("main_action"), dict) else "",
                            str(action.get("reaction_action", {}).get("action_id", "")) if isinstance(action, dict) and isinstance(action.get("reaction_action"), dict) else "",
                            *{str(edge.get("edge_id")) for edge in edges if isinstance(edge, dict)},
                        }
                        if str(body.get("wind_source")) not in entity_ids | source_event_ids:
                            errors.append(f"{hid}: softbody wind_source must resolve to an entity or action event")
                        if not coord(body.get("wind_direction")):
                            errors.append(f"{hid}: softbody wind_direction must be numeric XYZ")
                        if body.get("lag") not in {"LOW", "MEDIUM", "HIGH"} and not numeric(body.get("lag")):
                            errors.append(f"{hid}: softbody lag must be LOW/MEDIUM/HIGH or numeric")
                        if body.get("settle_condition") not in {"ON_WIND_DROP", "ON_ACTOR_SLOW", "ON_ARC_FINISH", "ON_FINAL_HOLD", "ON_SCENE_CUT"}:
                            errors.append(f"{hid}: unsupported softbody settle_condition")

                starts = xyz.get("entities_start", {}) if isinstance(xyz, dict) and isinstance(xyz.get("entities_start"), dict) else {}
                ends = xyz.get("entities_end", {}) if isinstance(xyz, dict) and isinstance(xyz.get("entities_end"), dict) else {}
                required_spatial_entities = {entity_base(item) for item in (action.get("participants", []) or [])} if isinstance(action, dict) else set()
                required_spatial_entities |= {str(prop.get("prop_id")) for prop in assets.get("hand_props", []) or [] if isinstance(prop, dict)}
                required_spatial_entities |= {str(body.get("softbody_id")) for body in assets.get("softbody", []) or [] if isinstance(body, dict)}
                for edge in edges:
                    if isinstance(edge, dict):
                        required_spatial_entities.add(entity_base(edge.get("actor")))
                        target_base = entity_base(edge.get("target"))
                        if target_base in entity_ids:
                            required_spatial_entities.add(target_base)
                missing_spatial = required_spatial_entities - set(starts) | required_spatial_entities - set(ends)
                if missing_spatial:
                    errors.append(f"{hid}: required spatial entities missing XYZ start/end coordinates: {sorted(missing_spatial)}")

            transition = shot.get("transition")
            required(transition, ["mechanism_id", "mechanism_type", "carrier", "last_visible_state", "first_visible_state", "locked", "allowed_change"], f"{hid}.transition", errors)
            if isinstance(transition, dict):
                mechanism_type = transition.get("mechanism_type")
                if mechanism_type not in {"CONTINUOUS", "OCCLUSION", "MATCH_MOTION", "SOUND_BRIDGE", "SCENE_CUT", "FINAL_HOLD"}:
                    errors.append(f"{hid}: unsupported transition mechanism_type")
                mech = str(transition.get("mechanism_id") or "")
                if mech:
                    transition_ids[mech] = transition_ids.get(mech, 0) + 1
                    if transition_ids[mech] > 1 and not transition.get("repeat_with_escalation"):
                        errors.append(f"{hid}: repeated transition {mech} requires repeat_with_escalation")
                if isinstance(action, dict) and transition.get("last_visible_state") != action.get("state_out"):
                    errors.append(f"{hid}: transition.last_visible_state must equal action state_out")
                image_exit = image.get("exit_motif") if isinstance(image, dict) else None
                audio_bridge = shot.get("audio", {}).get("bridge") if isinstance(shot.get("audio"), dict) else None
                if transition.get("carrier") not in {image_exit, audio_bridge} and str(transition.get("carrier")) not in entity_ids:
                    errors.append(f"{hid}: transition carrier must resolve to exit_motif, audio bridge or registered entity")
                if mechanism_type in {"OCCLUSION", "MATCH_MOTION"} and transition.get("carrier") != image_exit:
                    errors.append(f"{hid}: {mechanism_type} carrier must be the visible image exit_motif")
                if mechanism_type == "MATCH_MOTION":
                    required(transition.get("motion_bridge"), ["source_action_id", "target_action_id"], f"{hid}.transition.motion_bridge", errors)
                if mechanism_type == "SOUND_BRIDGE" and transition.get("carrier") != audio_bridge:
                    errors.append(f"{hid}: SOUND_BRIDGE carrier must resolve to audio.bridge")
                if mechanism_type == "FINAL_HOLD" and isinstance(action, dict):
                    if transition.get("first_visible_state") != transition.get("last_visible_state") or transition.get("first_visible_state") != action.get("state_out"):
                        errors.append(f"{hid}: FINAL_HOLD first/last visible state must equal action state_out")
                valid_path_prefixes = ("action.", "assets.", "xyz.", "audio", "image.")
                for path in list(transition.get("locked", []) or []) + list(transition.get("allowed_change", []) or []):
                    if not isinstance(path, str) or not (path == "audio" or path.startswith(valid_path_prefixes)):
                        errors.append(f"{hid}: illegal transition field path {path}")

            flat_shots.append((scene, shot))

        first_action = shots[0].get("action_chain", {}) if isinstance(shots[0], dict) else {}
        last_action = shots[-1].get("action_chain", {}) if isinstance(shots[-1], dict) else {}
        if scene.get("entrance_state") != first_action.get("state_in"):
            errors.append(f"{sid}: entrance_state must equal first shot state_in")
        if scene.get("exit_state") != last_action.get("state_out"):
            errors.append(f"{sid}: exit_state must equal last shot state_out")

    timeline.sort()
    active_support = set(map(str, data.get("load_plan", {}).get("active_support", []) or [])) if isinstance(data.get("load_plan"), dict) else set()
    if composition_catalog_used and "MIRROR_COMPOSITION" not in active_support:
        errors.append("composition catalog use requires MIRROR_COMPOSITION active support")
    scene_windows.sort()
    if timeline and timeline[0][0] != 0:
        errors.append("first shot must start at 0")
    for prev, cur in zip(timeline, timeline[1:]):
        if cur[0] < prev[1] - 1e-6:
            errors.append(f"timeline overlap: {prev[2]} and {cur[2]}")
        elif cur[0] > prev[1] + 1e-6:
            errors.append(f"timeline gap: {prev[2]} to {cur[2]}")
    if numeric(duration) and timeline and abs(float(duration) - timeline[-1][1]) > 1e-6:
        errors.append("last shot end must equal project.duration")

    for sound_id, sound in sound_registry.items():
        if not isinstance(sound, dict):
            continue
        shot_ids = sound.get("shot_ids", []) or []
        if not isinstance(shot_ids, list) or not shot_ids or any(str(item) not in seen_shot for item in shot_ids):
            errors.append(f"sound_registry.{sound_id}: shot_ids must reference existing shots")
        sync_id = str(sound.get("sync_to_action_or_image_evidence_id", ""))
        if sync_id not in action_registry and sync_id not in seen_shot:
            warnings.append(f"sound_registry.{sound_id}: sync ID is not a registered action or shot; verify image-evidence binding")

    for unit_id, unit in performance_units.items():
        if not isinstance(unit, dict):
            continue
        unit_shots = [str(item) for item in (unit.get("shot_ids", []) or [])]
        if not unit_shots or any(item not in seen_shot for item in unit_shots):
            errors.append(f"performance_units.{unit_id}: shot_ids must reference existing shots")
            continue
        if any(shot_source_beats.get(item) != str(unit.get("source_beat_id")) for item in unit_shots):
            errors.append(f"performance_units.{unit_id}: source_beat_id must match every linked shot")
        if any(str(unit.get("actor_id")) not in shot_scene_entities.get(item, set()) for item in unit_shots):
            errors.append(f"performance_units.{unit_id}: actor_id must resolve in every linked shot scene")
        for shot_id in unit_shots:
            scene_style_id = next(
                (
                    shot.get("style_contract_id")
                    for scene in scenes
                    if isinstance(scene, dict)
                    for shot in (scene.get("shots", []) or [])
                    if isinstance(shot, dict) and str(shot.get("shot_id")) == shot_id and shot.get("style_contract_id")
                ),
                None,
            )
            if scene_style_id and scene_style_id != style.get("style_contract_id"):
                errors.append(f"{shot_id}: shot style_contract_id drifts from project style contract")
    for prev, cur in zip(scene_windows, scene_windows[1:]):
        if abs(prev[1] - cur[0]) > 1e-6:
            errors.append(f"scene windows must meet: {prev[2]} to {cur[2]}")

    for (prev_scene, prev), (cur_scene, cur) in zip(flat_shots, flat_shots[1:]):
        pa, ca = prev.get("action_chain", {}), cur.get("action_chain", {})
        pt = prev.get("transition", {})
        allowed_changes = list(pt.get("allowed_change", []) or []) + list(authorized_changes)
        if pt.get("first_visible_state") != ca.get("state_in"):
            errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: transition.first_visible_state must equal next state_in")
        if pt.get("mechanism_type") == "MATCH_MOTION":
            bridge = pt.get("motion_bridge", {}) if isinstance(pt.get("motion_bridge"), dict) else {}
            if bridge.get("source_action_id") != pa.get("main_action", {}).get("action_id") or bridge.get("target_action_id") != ca.get("main_action", {}).get("action_id"):
                errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: MATCH_MOTION bridge must resolve source and target actions")
        action_diffs = diff_paths(pa.get("state_out"), ca.get("state_in"), "action")
        forbidden = sorted(path for path in action_diffs if not allowed(path, allowed_changes))
        if forbidden:
            errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: unauthorized action changes {forbidden}")

        prev_assets, cur_assets = prev.get("assets", {}), cur.get("assets", {})
        if prev_assets.get("identity") != cur_assets.get("identity") and not allowed("assets.identity", allowed_changes):
            errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: identity changed without authorization")
        if prev_assets.get("wardrobe") != cur_assets.get("wardrobe") and not allowed("assets.wardrobe", allowed_changes):
            errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: wardrobe changed without authorization")
        pp, cp = prop_map(prev_assets), prop_map(cur_assets)
        for prop_id in set(pp) | set(cp):
            path = f"assets.hand_props.{prop_id}"
            if prop_id not in pp or prop_id not in cp:
                previous_prop = pp.get(prop_id)
                if previous_prop and previous_prop.get("legal_exit") is not True:
                    errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: prop {prop_id} cannot exit while legal_exit is false")
                elif previous_prop and not previous_prop.get("legal_exit_event_id"):
                    errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: legal prop exit requires legal_exit_event_id")
                elif previous_prop:
                    valid_exit_events = {
                        str(prev.get("transition", {}).get("mechanism_id", "")),
                        str(prev.get("action_chain", {}).get("main_action", {}).get("action_id", "")),
                        *{
                            str(edge.get("edge_id"))
                            for edge in (prev.get("action_chain", {}).get("interaction_edges", []) or [])
                            if isinstance(edge, dict)
                        },
                    }
                    if str(previous_prop.get("legal_exit_event_id")) not in valid_exit_events:
                        errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: legal_exit_event_id does not resolve to a prior action or transition")
                elif not allowed(path, allowed_changes):
                    errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: prop {prop_id} appeared/disappeared without legal exit")
                continue
            for field in ("owner", "hand", "grip", "contact", "orientation"):
                field_path = f"{path}.{field}"
                if pp[prop_id].get(field) != cp[prop_id].get(field) and not allowed(field_path, allowed_changes):
                    errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: prop {prop_id} {field} changed without handoff")
            if pp[prop_id].get("state_out") != cp[prop_id].get("state_in") and not allowed(f"{path}.state", allowed_changes):
                errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: prop {prop_id} state handoff mismatch")

        pb, cb = softbody_map(prev_assets), softbody_map(cur_assets)
        if set(pb) != set(cb):
            errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: softbody identity changed across shots")
        for body_id in set(pb) & set(cb):
            if pb[body_id].get("owner") != cb[body_id].get("owner") or pb[body_id].get("anchor") != cb[body_id].get("anchor"):
                errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: softbody owner/anchor changed without authorization for {body_id}")
            if pb[body_id].get("residue") != cb[body_id].get("initial_motion") and not allowed(f"assets.softbody.{body_id}.motion", allowed_changes):
                errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: softbody residue handoff mismatch for {body_id}")

        pxyz, cxyz = prev.get("xyz", {}), cur.get("xyz", {})
        if str(pt.get("mechanism_type", "")).upper() == "CONTINUOUS":
            if pxyz.get("camera_end") != cxyz.get("camera_start"):
                errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: continuous camera handoff mismatch")
            p_frame = pxyz.get("camera_frame", {}) if isinstance(pxyz.get("camera_frame"), dict) else {}
            c_frame = cxyz.get("camera_frame", {}) if isinstance(cxyz.get("camera_frame"), dict) else {}
            if p_frame.get("screen_end_uvd") != c_frame.get("screen_start_uvd"):
                errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: continuous UVD handoff mismatch")
            if pxyz.get("axis_relation") != cxyz.get("axis_relation"):
                errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: continuous axis_relation handoff mismatch")
        if prev_scene.get("scene_id") == cur_scene.get("scene_id"):
            if pxyz.get("actor_end") != cxyz.get("actor_start") and not allowed("xyz.actor", allowed_changes):
                errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: actor XYZ handoff mismatch")
            p_entities = pxyz.get("entities_end", {}) if isinstance(pxyz.get("entities_end"), dict) else {}
            c_entities = cxyz.get("entities_start", {}) if isinstance(cxyz.get("entities_start"), dict) else {}
            if set(p_entities) != set(c_entities):
                errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: spatial entity set changed inside scene")
            for entity_id in set(p_entities) & set(c_entities):
                if p_entities[entity_id] != c_entities[entity_id] and not allowed(f"xyz.entities.{entity_id}", allowed_changes):
                    errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: entity XYZ handoff mismatch for {entity_id}")

        locked = pt.get("locked", []) or []
        prev_snapshot = {"assets": prev_assets, "action": pa.get("state_out"), "xyz": {"actor": pxyz.get("actor_end")}}
        cur_snapshot = {"assets": cur_assets, "action": ca.get("state_in"), "xyz": {"actor": cxyz.get("actor_start")}}
        locked_diffs = diff_paths(prev_snapshot, cur_snapshot)
        for lock in locked:
            if any(path == lock or path.startswith(f"{lock}.") for path in locked_diffs):
                errors.append(f"{prev.get('shot_id')}→{cur.get('shot_id')}: locked field changed: {lock}")

    return errors, warnings


def validate_narrative_document(narrative: dict[str, Any]) -> tuple[list[str], list[str]]:
    path = Path(__file__).with_name("validate_narrative_ir.py")
    spec = importlib.util.spec_from_file_location("prism_narrative_full_validator", path)
    if spec is None or spec.loader is None:
        return ["could not load narrative validator"], []
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module.validate(narrative)


def validate_against_narrative(
    director: dict[str, Any], narrative: dict[str, Any], errors: list[str], warnings: list[str]
) -> None:
    """Verify that director source identifiers exist in a supplied narrative IR."""
    n_source = narrative.get("source_contract", {}) if isinstance(narrative.get("source_contract"), dict) else {}
    d_source = director.get("source_contract", {}) if isinstance(director.get("source_contract"), dict) else {}
    if d_source.get("source_ir_id") != n_source.get("narrative_ir_id"):
        errors.append("director source_ir_id does not match narrative_ir_id")
    if str(d_source.get("source_ir_version")) != str(n_source.get("narrative_ir_version")):
        errors.append("director source_ir_version does not match narrative_ir_version")
    core = narrative.get("frozen_story_core", {}) if isinstance(narrative.get("frozen_story_core"), dict) else {}
    if d_source.get("frozen_story_core_id") != core.get("core_id"):
        errors.append("director frozen_story_core_id does not match narrative core_id")
    formal = director.get("runtime_context", {}).get("validation_mode") == "FORMAL_DELIVERY" if isinstance(director.get("runtime_context"), dict) else False
    if formal and (not isinstance(narrative.get("runtime_context"), dict) or narrative.get("runtime_context", {}).get("validation_mode") != "FORMAL_DELIVERY"):
        errors.append("formal director delivery requires a FORMAL_DELIVERY narrative IR")
    screenplay_receipts = [
        item
        for item in (narrative.get("layer_receipts", []) or [])
        if isinstance(item, dict) and item.get("layer_type") == "SCREENPLAY" and item.get("status") == "VALIDATED"
    ]
    if not any(
        str(item.get("layer_id")) == str(d_source.get("screenplay_layer_id"))
        and str(item.get("output_version")) == str(d_source.get("screenplay_version"))
        for item in screenplay_receipts
    ):
        errors.append("director screenplay_layer_id/version must resolve to a VALIDATED narrative SCREENPLAY receipt")

    n_scenes = narrative.get("structure", {}).get("scenes", []) if isinstance(narrative.get("structure"), dict) else []
    source_scene_ids = {str(scene.get("source_scene_id")) for scene in n_scenes if isinstance(scene, dict) and scene.get("source_scene_id")}
    source_beat_ids = {
        str(beat.get("beat_id"))
        for scene in n_scenes
        if isinstance(scene, dict)
        for beat in (scene.get("beats", []) or [])
        if isinstance(beat, dict) and beat.get("beat_id")
    }
    for scene in director.get("scenes", []) or []:
        if not isinstance(scene, dict):
            continue
        if str(scene.get("source_scene_id")) not in source_scene_ids:
            errors.append(f"{scene.get('scene_id')}: source_scene_id not found in narrative IR")
        for shot in scene.get("shots", []) or []:
            if not isinstance(shot, dict):
                continue
            if source_beat_ids and str(shot.get("source_beat_id")) not in source_beat_ids:
                errors.append(f"{shot.get('shot_id')}: source_beat_id not found in narrative IR")
    if not source_beat_ids and formal:
        errors.append("formal narrative IR requires a source beat registry for director cross-check")
    elif not source_beat_ids:
        warnings.append("narrative IR contains no beat registry; source_beat_id existence was not cross-checked")


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", type=Path)
    parser.add_argument("--narrative-ir", type=Path)
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()
    try:
        data = load_document(args.input)
        errors, warnings = validate(data, narrative_provided=bool(args.narrative_ir))
        if args.narrative_ir:
            narrative = load_document(args.narrative_ir)
            narrative_errors, narrative_warnings = validate_narrative_document(narrative)
            errors.extend(f"narrative_ir: {item}" for item in narrative_errors)
            warnings.extend(f"narrative_ir: {item}" for item in narrative_warnings)
            validate_against_narrative(data, narrative, errors, warnings)
    except Exception as exc:
        errors, warnings = [f"load failure: {exc}"], []
    result = {"status": "PASS" if not errors else "FAIL", "errors": errors, "warnings": warnings}
    print(json.dumps(result, ensure_ascii=False, indent=2) if args.json else "\n".join([result["status"], *[f"ERROR: {e}" for e in errors], *[f"WARN: {w}" for w in warnings]]))
    return 0 if not errors else 1


if __name__ == "__main__":
    sys.exit(main())
