#!/usr/bin/env python3
"""Run positive fixtures and adversarial mutations for the PRISM validators."""

from __future__ import annotations

import copy
import importlib.util
import json
import sys
from pathlib import Path
from typing import Any, Callable


ROOT = Path(__file__).resolve().parent.parent


def load_module(name: str, path: Path) -> Any:
    spec = importlib.util.spec_from_file_location(name, path)
    if spec is None or spec.loader is None:
        raise RuntimeError(f"cannot load {path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


DIRECTOR = load_module("prism_director_validator", Path(__file__).with_name("validate_director_ir.py"))
NARRATIVE = load_module("prism_narrative_validator", Path(__file__).with_name("validate_narrative_ir.py"))
SCREENPLAY = load_module("prism_screenplay_validator", Path(__file__).with_name("validate_screenplay_ir.py"))
WORKFLOW = load_module("prism_workflow_validator", Path(__file__).with_name("validate_workflow_plan.py"))
CONTENT_GAP = load_module("juben_content_gap_validator", Path(__file__).with_name("validate_content_gap_repair.py"))
KNOWLEDGE = load_module("juben_knowledge_validator", Path(__file__).with_name("validate_knowledge_claims.py"))
PACKAGE = load_module("juben_package_validator", Path(__file__).with_name("validate_skill_package.py"))
SOURCE_LEDGER = load_module("juben_source_ledger_validator", Path(__file__).with_name("validate_source_ledger.py"))
REFERENCE_ABSORPTION = load_module("juben_reference_absorption_validator", Path(__file__).with_name("validate_reference_absorption.py"))


def mutate_gap_remove_freeze_manifest(doc: dict[str, Any]) -> None:
    doc["freeze_manifest"] = []


def mutate_gap_single_patch(doc: dict[str, Any]) -> None:
    doc["patch_options"] = doc["patch_options"][:1]


def mutate_gap_duplicate_delta(doc: dict[str, Any]) -> None:
    doc["patch_options"][1]["proposed_delta"] = copy.deepcopy(doc["patch_options"][0]["proposed_delta"])


def mutate_gap_no_conservative(doc: dict[str, Any]) -> None:
    doc["patch_options"][0]["mode"] = "STRUCTURAL"


def mutate_gap_drop_hard_lock(doc: dict[str, Any]) -> None:
    doc["patch_options"][0]["preserved_locks"] = []


def mutate_gap_unknown_decision(doc: dict[str, Any]) -> None:
    doc["decision_receipt"]["accepted_patch_ids"] = ["PATCH-UNKNOWN"]


def mutate_gap_break_hard_lock(doc: dict[str, Any]) -> None:
    doc["regression_receipt"]["hard_locks_preserved"] = False


def mutate_gap_new_contradiction(doc: dict[str, Any]) -> None:
    doc["regression_receipt"]["new_contradictions"] = ["ending lock broken"]


def mutate_controller_count(doc: dict[str, Any]) -> None:
    doc["authority_contract"]["controller_count"] = 2


def mutate_bad_xyz(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["xyz"]["actor_start"] = "left-of-frame"


def mutate_shanyin_invoked(doc: dict[str, Any]) -> None:
    doc["shanyin_runtime_receipt"]["invoked"] = False


def mutate_feiran_hard(doc: dict[str, Any]) -> None:
    doc["source_contract"]["candidate_rules_in_use"][0]["enforcement"] = "HARD"


def mutate_prop_hand(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][1]["assets"]["hand_props"][0]["hand"] = "left"


def mutate_missing_carrier(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["transition"]["carrier"] = ""


def mutate_delta_mismatch(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["image_chain"]["state_delta_id"] = "WRONG"


def mutate_main_action_string(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["action_chain"]["main_action"] = "perform several actions"


def mutate_missing_contact_edge(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["action_chain"]["interaction_edges"] = []


def mutate_softbody_missing(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["assets"]["softbody"] = []


def mutate_missing_shanyin_receipt(doc: dict[str, Any]) -> None:
    doc.pop("shanyin_runtime_receipt", None)


def mutate_story_owner_mirror(doc: dict[str, Any]) -> None:
    doc["authority_contract"]["field_owners"]["story_truth"] = "MIRROR_COMPOSITION_SUPPORT"


def mutate_transition_owner_prop(doc: dict[str, Any]) -> None:
    doc["authority_contract"]["field_owners"]["final_transition"] = "WANFU_PROP_SUPPORT"


def mutate_chinese_feiran_hard(doc: dict[str, Any]) -> None:
    doc["source_contract"]["candidate_rules_in_use"][0]["source"] = "斐然导演"
    doc["source_contract"]["candidate_rules_in_use"][0]["enforcement"] = "HARD"


def mutate_forbidden_load_plan(doc: dict[str, Any]) -> None:
    doc["load_plan"]["active_support"] = ["FEIRAN_ALL_HARD", "MIRROR_FULL_LIBRARY", "SHANYIN_EIGHT_STEPS"]


def mutate_fake_tested_claim(doc: dict[str, Any]) -> None:
    doc["claim_contract"]["effect_status"] = "TESTED"
    doc["claim_contract"]["comparison_evidence"] = "trust_me"


def mutate_missing_rejected_rules(doc: dict[str, Any]) -> None:
    doc["source_contract"].pop("rejected_rules", None)


def mutate_composition_overload(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["image_chain"]["composition_mechanisms"] = [f"M{i}" for i in range(7)]


def mutate_method_as_asset_lock(doc: dict[str, Any]) -> None:
    doc["request_contract"]["creative_or_asset_locks"].append(
        {"lock_id": "BAD-METHOD-LOCK", "type": "ASSET", "source_id": "USER", "target_field": "project.asset", "raw_text": "斐然全部硬规则"}
    )


def mutate_entity_teleport(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["xyz"]["entities_end"]["folding-fan"] = [999, 999, 999]


def mutate_negative_uvd(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["xyz"]["camera_frame"]["screen_end_uvd"] = [0.0, 0.0, -9.0]


def mutate_uvd_direction(doc: dict[str, Any]) -> None:
    frame = doc["scenes"][0]["shots"][0]["xyz"]["camera_frame"]
    frame["screen_start_uvd"] = [0.9, 0.0, 2.0]
    frame["screen_end_uvd"] = [-0.9, 0.0, 2.0]
    doc["scenes"][0]["shots"][0]["xyz"]["screen_direction"] = "left-to-right"


def mutate_no_observable_delta(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["image_chain"]["observable_delta"] = "nothing changes"


def mutate_softbody_values(doc: dict[str, Any]) -> None:
    body = doc["scenes"][0]["shots"][0]["assets"]["softbody"][0]
    body["wind_direction"] = "逆风乱飞"
    body["settle_condition"] = "never"


def mutate_primary_actor_mismatch(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["action_chain"]["primary_actor"] = "ghost"


def mutate_compound_verb(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["action_chain"]["main_action"]["verb"] = "run-turn-jump-open-close"


def mutate_route_list(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["xyz"]["route"] = ["unregistered-zone"]


def mutate_contact_nonsense(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["xyz"]["contact_points"] = ["none"]


def mutate_prop_swap(doc: dict[str, Any]) -> None:
    prop = doc["scenes"][0]["shots"][1]["assets"]["hand_props"][0]
    prop["prop_id"] = "phone"
    doc["scenes"][0]["shots"][0]["transition"]["allowed_change"].extend(
        ["assets.hand_props.folding-fan", "assets.hand_props.phone"]
    )


def mutate_unknown_carrier(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["transition"]["carrier"] = "nonexistent-magic-teleport"


def mutate_frozen_wardrobe(doc: dict[str, Any]) -> None:
    doc["project"]["asset_registry"]["unauthorized-black-costume"] = {"type": "wardrobe"}
    for scene in doc["scenes"]:
        for shot in scene["shots"]:
            shot["assets"]["wardrobe"] = "unauthorized-black-costume"


def mutate_prop_action_contradiction(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["assets"]["hand_props"][0]["state_out"] = "destroyed"


def mutate_scene_boundary(doc: dict[str, Any]) -> None:
    doc["scenes"][1]["entrance_state"] = {"location": "wrong-universe"}


def mutate_story_owner(doc: dict[str, Any]) -> None:
    doc["authority_contract"]["field_owners"]["story_truth"] = "SHANYIN"


def mutate_bad_causal_connector(doc: dict[str, Any]) -> None:
    doc["structure"]["scenes"][1]["causal_connector"] = "THEN"


def mutate_climax_choice(doc: dict[str, Any]) -> None:
    doc["climax_gate"]["protagonist_choice"] = "等待别人处理"


def mutate_evidence_order(doc: dict[str, Any]) -> None:
    doc["information"]["ledger"][0]["planted_scene_id"] = "N06"
    doc["information"]["ledger"][0]["verified_scene_id"] = "N01"


def mutate_no_agency(doc: dict[str, Any]) -> None:
    doc["structure"]["scenes"][3]["protagonist_choice"] = "none"


def mutate_noncreative_plot_owner(doc: dict[str, Any]) -> None:
    doc["authority_contract"]["field_owners"]["plot"] = "JINGLV"


def mutate_unknown_episode_turn(doc: dict[str, Any]) -> None:
    doc["episode_contract"]["act_or_sequence_turns"][0]["scene_id"] = "NO_SUCH_SCENE"


def mutate_episode_duration(doc: dict[str, Any]) -> None:
    doc["episode_contract"]["requested_duration_seconds"] = 999


def mutate_missing_information_access(doc: dict[str, Any]) -> None:
    doc["information"]["ledger"][0].pop("access", None)


def mutate_decisive_clue_after_climax(doc: dict[str, Any]) -> None:
    item = doc["information"]["ledger"][0]
    item["planted_scene_id"] = "N08"
    item["verified_scene_id"] = "N08"
    item["reveal_scene_id"] = "N08"
    item["payoff_scene_id"] = "N08"


def mutate_unestablished_climax_resource(doc: dict[str, Any]) -> None:
    doc["climax_gate"]["resource_ids"].append("MAGIC_KEY")
    doc["climax_gate"]["resource_setup_scene_ids"]["MAGIC_KEY"] = "N06"


def mutate_broken_layer_chain(doc: dict[str, Any]) -> None:
    doc["layer_receipts"][0]["source_layer_id"] = "NONEXISTENT"


def mutate_unknown_owner_key(doc: dict[str, Any]) -> None:
    doc["authority_contract"]["field_owners"]["scene_outcome_extra"] = "CREATIVE_TO_NARRATIVE"


def mutate_shanyin_active_source(doc: dict[str, Any]) -> None:
    doc["source_contract"]["active_sources"] = [
        item for item in doc["source_contract"]["active_sources"] if "SHANYIN" not in str(item).upper() and "山音" not in str(item)
    ]


def mutate_shanyin_registry_verified(doc: dict[str, Any]) -> None:
    doc["source_registry"]["SHANYIN"]["status"] = "SOURCE_VERIFIED"
    doc["source_registry"]["SHANYIN"]["source_hash"] = "fake"


def mutate_shanyin_gap_localized_bypass(doc: dict[str, Any]) -> None:
    doc["source_contract"]["source_gaps"] = [{"来源": "山音", "状态": "正文缺失"}]


def mutate_feiran_production_constraint(doc: dict[str, Any]) -> None:
    doc["project"]["production_constraints"].append("FEIRAN_ALL_HARD")


def mutate_feiran_source_wash(doc: dict[str, Any]) -> None:
    rule = doc["source_contract"]["candidate_rules_in_use"][0]
    rule["source_id"] = "USER_REQUEST"
    rule["enforcement"] = "HARD"


def mutate_structured_fake_tested(doc: dict[str, Any]) -> None:
    doc["claim_contract"] = {
        "effect_status": "TESTED",
        "comparison_scope": "REGISTERED_PLATFORM_MODEL",
        "claim_level": "TESTED_IN_REGISTERED_SCOPE",
        "claim_template_id": "CLAIM_TESTED_REGISTERED_SCOPE_ONLY",
        "comparison_evidence": {
            "platform_model": "imaginary-model",
            "abc_case_ids": ["A", "B", "C"],
            "blind_review_id": "BLIND",
            "failure_ledger_id": "FAILURES",
            "regression_id": "REGRESSION",
        },
    }


def mutate_embedded_standalone(doc: dict[str, Any]) -> None:
    doc["authority_contract"]["controller"] = "PRISM_STANDALONE"


def mutate_shanyin_request_receipt_mismatch(doc: dict[str, Any]) -> None:
    doc["shanyin_runtime_receipt"]["requested"] = False


def mutate_method_paraphrase_as_lock(doc: dict[str, Any]) -> None:
    doc["request_contract"]["creative_or_asset_locks"].append(
        {"lock_id": "BAD-PARAPHRASE", "type": "ASSET", "source_id": "USER", "target_field": "method.workflow", "raw_text": "采用那套完整工作流"}
    )


def mutate_notice_coverage(doc: dict[str, Any]) -> None:
    notice = doc["request_contract"]["method_deviation_notice"]
    notice["required"] = True
    notice["emitted"] = True


def mutate_disguised_composition_library(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["image_chain"]["composition_mechanisms"] = ["MIRROR_FULL_LIBRARY"]


def mutate_support_without_owner(doc: dict[str, Any]) -> None:
    doc["authority_contract"]["field_owners"].pop("composition", None)


def mutate_malformed_rejected_rule(doc: dict[str, Any]) -> None:
    doc["source_contract"]["rejected_rules"][0].pop("affected_field", None)


def mutate_free_effect_claim(doc: dict[str, Any]) -> None:
    doc["claim_contract"]["effect_claim_text"] = "顶级效果已验证"


def mutate_duplicate_director_layer(doc: dict[str, Any]) -> None:
    doc["layer_receipts"].append(copy.deepcopy(doc["layer_receipts"][0]))


def mutate_unknown_director_layer(doc: dict[str, Any]) -> None:
    doc["layer_receipts"][0]["layer_type"] = "BANANA"


def mutate_director_source_version(doc: dict[str, Any]) -> None:
    doc["layer_receipts"][0]["source_version"] = "wrong"


def mutate_formal_without_narrative(doc: dict[str, Any]) -> None:
    doc["runtime_context"]["validation_mode"] = "FORMAL_DELIVERY"


def mutate_participant_without_xyz(doc: dict[str, Any]) -> None:
    scene = doc["scenes"][0]
    scene["entity_registry"]["character-B"] = {"type": "character"}
    scene["shots"][0]["action_chain"]["participants"].append("character-B")


def mutate_two_props_one_hand(doc: dict[str, Any]) -> None:
    scene = doc["scenes"][0]
    shot = scene["shots"][0]
    doc["project"]["asset_registry"]["phone"] = {"type": "handheld-prop"}
    scene["entity_registry"]["phone"] = {"type": "handheld-prop"}
    shot["xyz"]["entities_start"]["phone"] = [-0.43, 0.18, 1.05]
    shot["xyz"]["entities_end"]["phone"] = [-0.06, 0.50, 1.08]
    shot["assets"]["hand_props"].append({
        "prop_id": "phone", "owner": "character-A", "hand": "right", "grip": "grip", "contact": "palm", "orientation": "forward",
        "state_ref": "phone", "state_in": "held", "state_out": "held", "legal_exit": False,
    })


def mutate_contact_ledger_mismatch(doc: dict[str, Any]) -> None:
    contact = doc["scenes"][0]["shots"][0]["xyz"]["contact_points"][0]
    contact["target_entity"] = "garden-stone-floor"
    contact["target_part"] = "surface"


def mutate_continuous_camera_jump(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["xyz"]["camera_end"] = [4.0, 4.0, 2.0]


def mutate_continuous_uvd_jump(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["xyz"]["camera_frame"]["screen_end_uvd"] = [0.9, 0.9, 2.95]


def mutate_nonexistent_action_target(doc: dict[str, Any]) -> None:
    action = doc["scenes"][0]["shots"][0]["action_chain"]["main_action"]
    action["target"] = "nonexistent-entity"
    action["requires_contact"] = False
    doc["scenes"][0]["shots"][0]["action_chain"]["interaction_edges"] = []


def mutate_wrong_image_evidence_field(doc: dict[str, Any]) -> None:
    image = doc["scenes"][0]["shots"][0]["image_chain"]
    image["evidence_registry"]["D01:emotion"]["field"] = "sky_color"


def mutate_compound_reaction(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["action_chain"]["reaction_action"]["verb"] = "run-turn-jump"


def mutate_softbody_anchor(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["assets"]["softbody"][0]["anchor"] = "nonexistent-anchor"


def mutate_softbody_wind_source(doc: dict[str, Any]) -> None:
    doc["scenes"][1]["shots"][0]["assets"]["softbody"][0]["wind_source"] = "magic-source"


def mutate_invisible_occlusion_carrier(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][1]["transition"]["carrier"] = "garden-wind"


def mutate_unknown_axis_enum(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["xyz"]["axis_relation"] = "BANANA"


def mutate_unknown_screen_direction(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["xyz"]["screen_direction"] = "BANANA"


def mutate_final_hold_first_state(doc: dict[str, Any]) -> None:
    doc["scenes"][-1]["shots"][-1]["transition"]["first_visible_state"] = {"wrong": "state"}


def mutate_match_motion_bridge(doc: dict[str, Any]) -> None:
    doc["scenes"][1]["shots"][0]["transition"]["motion_bridge"]["target_action_id"] = "NO_ACTION"


def mutate_duplicate_director_source_scene(doc: dict[str, Any]) -> None:
    doc["scenes"][1]["source_scene_id"] = doc["scenes"][0]["source_scene_id"]


def mutate_unknown_narrative_owner(doc: dict[str, Any]) -> None:
    doc["authority_contract"]["field_owners"]["scene_outcome_extra"] = "CREATIVE_TO_NARRATIVE"


def mutate_narrative_shanyin_active(doc: dict[str, Any]) -> None:
    doc["source_contract"]["active_sources"] = [item for item in doc["source_contract"]["active_sources"] if "SHANYIN" not in str(item).upper()]


def mutate_duplicate_a_story(doc: dict[str, Any]) -> None:
    doc["episode_contract"]["a_story_scene_ids"].append(doc["episode_contract"]["a_story_scene_ids"][0])


def mutate_duplicate_turn(doc: dict[str, Any]) -> None:
    doc["episode_contract"]["act_or_sequence_turns"].append(copy.deepcopy(doc["episode_contract"]["act_or_sequence_turns"][0]))


def mutate_task_duration(doc: dict[str, Any]) -> None:
    doc["task_contract"]["requested_duration_seconds"] = 60


def mutate_decisive_flag_string(doc: dict[str, Any]) -> None:
    doc["information"]["ledger"][0]["required_for_climax"] = "true"


def mutate_no_decisive_clue(doc: dict[str, Any]) -> None:
    for item in doc["information"]["ledger"]:
        item["required_for_climax"] = False


def mutate_duplicate_truth_id(doc: dict[str, Any]) -> None:
    doc["information"]["ledger"][1]["truth_id"] = doc["information"]["ledger"][0]["truth_id"]


def mutate_payoff_before_reveal(doc: dict[str, Any]) -> None:
    item = doc["information"]["ledger"][0]
    item["payoff_scene_id"] = "N02"


def mutate_rejected_upstream_layer(doc: dict[str, Any]) -> None:
    doc["layer_receipts"][0]["status"] = "REJECTED"
    doc["layer_receipts"].append({
        "layer_type": "SCREENPLAY", "layer_id": "SCREENPLAY-01", "status": "VALIDATED",
        "source_layer_id": doc["layer_receipts"][0]["layer_id"], "source_version": doc["layer_receipts"][0]["output_version"], "output_version": "1.0",
        "preserved_truth_ids": [], "transformed_field_ids": [], "proposed_story_changes": [], "creative_decision_id": "DEC-02", "rejected_overrides": [],
    })


def mutate_duplicate_narrative_layer(doc: dict[str, Any]) -> None:
    doc["layer_receipts"].append(copy.deepcopy(doc["layer_receipts"][0]))


def mutate_pending_forward_cursor(doc: dict[str, Any]) -> None:
    doc["layer_receipts"][0]["status"] = "PENDING_CREATIVE_REVIEW"


def mutate_unknown_narrative_layer(doc: dict[str, Any]) -> None:
    doc["layer_receipts"][0]["layer_type"] = "BANANA"


def mutate_narrative_source_version(doc: dict[str, Any]) -> None:
    doc["layer_receipts"][0]["source_version"] = "wrong"


def mutate_duplicate_source_scene(doc: dict[str, Any]) -> None:
    doc["structure"]["scenes"][1]["source_scene_id"] = doc["structure"]["scenes"][0]["source_scene_id"]


def mutate_narrative_registry_verified(doc: dict[str, Any]) -> None:
    doc["source_registry"]["SHANYIN"]["source_hash"] = "fake"


def mutate_director_manifest_self_sign(doc: dict[str, Any]) -> None:
    doc["source_registry"]["SHANYIN"]["manifest_id"] = "ATTACKER-MANIFEST"
    doc["source_registry"]["SHANYIN"]["validation_receipt_id"] = "ATTACKER-RECEIPT"
    doc["shanyin_runtime_receipt"]["source_manifest_id"] = "ATTACKER-MANIFEST"
    doc["shanyin_runtime_receipt"]["validation_receipt_id"] = "ATTACKER-RECEIPT"


def mutate_narrative_manifest_self_sign(doc: dict[str, Any]) -> None:
    doc["source_registry"]["SHANYIN"]["manifest_id"] = "ATTACKER-MANIFEST"
    doc["source_registry"]["SHANYIN"]["validation_receipt_id"] = "ATTACKER-RECEIPT"
    doc["shanyin_runtime_receipt"]["source_manifest_id"] = "ATTACKER-MANIFEST"
    doc["shanyin_runtime_receipt"]["validation_receipt_id"] = "ATTACKER-RECEIPT"


def mutate_narrative_receipt_contradiction(doc: dict[str, Any]) -> None:
    doc["shanyin_runtime_receipt"]["fallback"] = "SHANYIN_ORIGINAL_EIGHT_STEP"


def mutate_project_overclaim(doc: dict[str, Any]) -> None:
    doc["project"]["delivery_claim"] = "完全复刻原版，同等顶级导演水准"


def mutate_feiran_story_scope(doc: dict[str, Any]) -> None:
    doc["source_contract"]["candidate_rules_in_use"][0]["field_scope"] = "story.plot"


def mutate_empty_tested_evidence_records(doc: dict[str, Any]) -> None:
    mutate_structured_fake_tested(doc)
    doc["evidence_registry"] = {key: {} for key in ("A", "B", "C", "BLIND", "FAILURES", "REGRESSION")}


def mutate_contradictory_notice(doc: dict[str, Any]) -> None:
    doc["request_contract"]["method_deviation_notice"]["notice_text"] = "山音原版八步已经完整执行，效果与原版一致"


def mutate_named_method_creative_lock(doc: dict[str, Any]) -> None:
    doc["request_contract"]["creative_or_asset_locks"].append({
        "lock_id": "BAD-CREATIVE-METHOD", "type": "CREATIVE", "source_id": "USER", "target_field": "story.theme",
        "raw_text": "采用斐然导演体系的每一条规范，全部作为不可违背的强制标准",
    })


def mutate_rejected_method_identity(doc: dict[str, Any]) -> None:
    doc["request_contract"]["rejected_method_requests"].append({
        "request_id": "SHANYIN-REQ-01",
        "source_id": "OTHER",
        "method_id": "UNRELATED_METHOD",
        "reason_code": "ACCEPTED",
    })


def mutate_method_source_spoof(doc: dict[str, Any]) -> None:
    doc["request_contract"]["method_requests"][0]["source_id"] = "OTHER"


def mutate_composition_without_support(doc: dict[str, Any]) -> None:
    doc["load_plan"]["active_support"].remove("MIRROR_COMPOSITION")


def mutate_empty_director_receipt(doc: dict[str, Any]) -> None:
    receipt = doc["layer_receipts"][0]
    receipt["creative_decision_id"] = ""
    receipt["preserved_truth_ids"] = []
    receipt["transformed_field_ids"] = []


def mutate_unknown_director_decision(doc: dict[str, Any]) -> None:
    doc["layer_receipts"][0]["creative_decision_id"] = "NO_DECISION"


def mutate_formal_missing_current_layer(doc: dict[str, Any]) -> None:
    doc["runtime_context"]["validation_mode"] = "FORMAL_DELIVERY"
    doc["task_contract"]["current_delivery_layers"] = ["STORY_BLUEPRINT", "SCREENPLAY"]


def mutate_empty_narrative_receipt(doc: dict[str, Any]) -> None:
    receipt = doc["layer_receipts"][0]
    receipt["creative_decision_id"] = ""
    receipt["preserved_truth_ids"] = []
    receipt["transformed_field_ids"] = []


def mutate_span_duration_all_60(doc: dict[str, Any]) -> None:
    doc["task_contract"]["requested_duration_seconds"] = 60
    doc["episode_contract"]["requested_duration_seconds"] = 60
    doc["structure"]["total_duration"] = 60
    count = len(doc["structure"]["scenes"])
    cursor = 0.0
    for index, scene in enumerate(doc["structure"]["scenes"]):
        end = 60.0 if index == count - 1 else round((index + 1) * 60.0 / count, 6)
        scene["t_in"] = cursor
        scene["t_out"] = end
        cursor = end


def mutate_cross_scene_continuous_jump(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][1]["transition"]["mechanism_type"] = "CONTINUOUS"


def mutate_reaction_unknown_target(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["action_chain"]["reaction_action"]["target"] = "nonexistent-reaction-target"


def mutate_reaction_multiple_subactions(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["action_chain"]["reaction_action"]["sub_actions"] = ["blink", "smile"]


def mutate_shared_spatial_contact(doc: dict[str, Any]) -> None:
    shot = doc["scenes"][0]["shots"][0]
    duplicate = copy.deepcopy(shot["action_chain"]["interaction_edges"][0])
    duplicate["edge_id"] = "E01-DUP"
    shot["action_chain"]["interaction_edges"].append(duplicate)
    shot["image_chain"]["visible_contact_ids"].append("E01-DUP")


def mutate_edge_contact_part(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["action_chain"]["interaction_edges"][0]["contact_part"] = "left-elbow"


def mutate_score_under_no_bgm(doc: dict[str, Any]) -> None:
    doc["sound_registry"]["SFX-FAN-01"]["music_classification"] = "SCORE"


def mutate_scene_subtitles(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["subtitles"] = "解释性字幕"


def mutate_sound_missing_trigger(doc: dict[str, Any]) -> None:
    doc["sound_registry"]["SFX-FAN-01"]["physical_or_world_trigger"] = ""


def mutate_sound_unknown_shot(doc: dict[str, Any]) -> None:
    doc["sound_registry"]["SFX-FAN-01"]["shot_ids"] = ["NO-SHOT"]


def mutate_performance_no_trigger(doc: dict[str, Any]) -> None:
    doc["performance_units"]["PU-POWER-UNDERPLAY-01"]["stimulus_or_trigger"] = ""


def mutate_performance_mind_reading(doc: dict[str, Any]) -> None:
    doc["performance_units"]["PU-POWER-UNDERPLAY-01"]["rendered_evidence"] = "她内心十分自信，仿佛恩赐"


def mutate_performance_unknown_prop_action(doc: dict[str, Any]) -> None:
    doc["performance_units"]["PU-POWER-UNDERPLAY-01"]["prop_action_id"] = "NO-ACTION"


def mutate_performance_beat_mismatch(doc: dict[str, Any]) -> None:
    doc["performance_units"]["PU-POWER-UNDERPLAY-01"]["source_beat_id"] = "NO-BEAT"


def mutate_performance_actor_missing(doc: dict[str, Any]) -> None:
    doc["performance_units"]["PU-POWER-UNDERPLAY-01"]["actor_id"] = "ghost-actor"


def mutate_named_director_style(doc: dict[str, Any]) -> None:
    doc["style_contract"]["visual_thesis"] = "诺兰式东方星象变身"


def mutate_style_native_guarantee(doc: dict[str, Any]) -> None:
    doc["style_contract"]["finish_target"] = "NATIVE_4K_GUARANTEED"


def mutate_shot_style_drift(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["shots"][0]["style_contract_id"] = "OTHER-STYLE"


def mutate_missing_concept(doc: dict[str, Any]) -> None:
    doc.pop("concept_contract", None)


def mutate_unapproved_concept(doc: dict[str, Any]) -> None:
    doc["concept_contract"]["status"] = "SHANYIN_PROPOSED"


def mutate_bad_concept_mode(doc: dict[str, Any]) -> None:
    doc["concept_contract"]["mode"] = "COOL_IDEA"


def mutate_short_consequence_ladder(doc: dict[str, Any]) -> None:
    doc["concept_contract"]["consequence_ladder"] = doc["concept_contract"]["consequence_ladder"][:2]


def mutate_single_domain_ladder(doc: dict[str, Any]) -> None:
    for item in doc["concept_contract"]["consequence_ladder"]:
        item["domain"] = "SCALE"


def mutate_missing_form_necessity(doc: dict[str, Any]) -> None:
    doc["concept_contract"]["form_contract"]["necessity"] = ""


def mutate_missing_motif_mutation(doc: dict[str, Any]) -> None:
    doc["concept_contract"]["clean_motif"]["mutation_rule"] = ""


def mutate_core_concept_mismatch(doc: dict[str, Any]) -> None:
    doc["frozen_story_core"]["concept_id"] = "OTHER-CONCEPT"


def mutate_unknown_concept_decision(doc: dict[str, Any]) -> None:
    doc["concept_contract"]["creative_decision_id"] = "NO-DECISION"


def mutate_shanyin_fake_version(doc: dict[str, Any]) -> None:
    doc["source_registry"]["SHANYIN"]["source_version"] = "v9.9-OFFICIAL"


def mutate_shanyin_fake_authorship(doc: dict[str, Any]) -> None:
    doc["source_registry"]["SHANYIN"]["authorship_status"] = "AUTHOR_VERIFIED"


def mutate_missing_scene_life(doc: dict[str, Any]) -> None:
    doc.pop("scene_life_contract", None)


def mutate_missing_relationships(doc: dict[str, Any]) -> None:
    doc.pop("relationships", None)


def mutate_missing_expression(doc: dict[str, Any]) -> None:
    doc.pop("expression", None)


def mutate_scene_life_missing_scene(doc: dict[str, Any]) -> None:
    doc["scene_life_contract"]["ledger"].pop()


def mutate_bad_scene_entry_mode(doc: dict[str, Any]) -> None:
    doc["scene_life_contract"]["ledger"][0]["entry_mode"] = "PRETTY_ESTABLISHING_SHOT"


def mutate_empty_sensory_evidence(doc: dict[str, Any]) -> None:
    doc["scene_life_contract"]["ledger"][0]["sensory_evidence"] = []


def mutate_active_environment_without_cause(doc: dict[str, Any]) -> None:
    response = doc["scene_life_contract"]["ledger"][0]["environment_response"]
    response["trigger_type"] = "NONE"


def mutate_offscreen_active_without_evidence(doc: dict[str, Any]) -> None:
    doc["scene_life_contract"]["ledger"][0]["offscreen_world"]["evidence"] = ""


def mutate_bad_ending_emotion(doc: dict[str, Any]) -> None:
    doc["ending_contract"]["emotional_result"] = "EVERYONE_LIVES_SO_HE"


def mutate_open_ending_without_debt(doc: dict[str, Any]) -> None:
    doc["ending_contract"]["causal_closure"] = "OPEN"
    doc["ending_contract"]["open_debts"] = []


def mutate_false_ending_without_depth(doc: dict[str, Any]) -> None:
    doc["ending_contract"]["revelation_mode"] = "FALSE_ENDING"
    doc["ending_contract"]["deep_result"] = doc["ending_contract"]["surface_result"]


def mutate_missing_ending_dimension(doc: dict[str, Any]) -> None:
    doc["ending_contract"]["settlement"].pop("inner_need")


def mutate_ending_evidence_unknown_scene(doc: dict[str, Any]) -> None:
    doc["ending_contract"]["settlement"]["world"]["evidence_scene_id"] = "NO-SCENE"


def mutate_ending_drops_climax_promise(doc: dict[str, Any]) -> None:
    doc["ending_contract"]["promise_ids_paid"] = ["P_DRAMATIC"]


def mutate_screenplay_missing_scene_owner(doc: dict[str, Any]) -> None:
    doc["scenes"][0].pop("scene_owner")


def mutate_screenplay_multi_primary(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["beats"][0]["primary_function"] = ["ORIENT", "REVEAL"]


def mutate_screenplay_attention_overload(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["beats"][0]["secondary_functions"] = ["PRESSURE", "REVEAL"]


def mutate_screenplay_missing_expectation_gap(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["beats"][0].pop("expectation_gap")


def mutate_screenplay_camera_leak(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["beats"][0]["director_instruction"] = "高空俯拍后慢放特写"


def mutate_screenplay_ambiguous_referent(doc: dict[str, Any]) -> None:
    unit = doc["scenes"][0]["dialogue_units"][0]
    unit["referent_status"] = "INTENTIONAL_AMBIGUITY"
    unit["referent_anchors"] = []


def mutate_screenplay_missing_response(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["dialogue_units"][0]["listener_response"] = ""


def mutate_screenplay_unknown_voiceprint(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["dialogue_units"][0]["voiceprint_id"] = "VOICE-NOBODY"


def mutate_screenplay_runtime_overload(doc: dict[str, Any]) -> None:
    budget = doc["scenes"][0]["runtime_budget"]
    budget["spoken_seconds"] = 20
    budget["estimated_occupied_seconds"] = 42
    budget["reserve_seconds"] = 0


def mutate_screenplay_no_value_change(doc: dict[str, Any]) -> None:
    doc["scenes"][0]["exit_value"]["state"] = doc["scenes"][0]["entry_value"]["state"]


def mutate_screenplay_bad_handoff(doc: dict[str, Any]) -> None:
    doc["scenes"][1]["handoff_from_previous"] = "NONE_FIRST"


def mutate_screenplay_duplicate_beat(doc: dict[str, Any]) -> None:
    doc["scenes"][1]["beats"][0]["beat_id"] = doc["scenes"][0]["beats"][0]["beat_id"]


def mutate_screenplay_zero_asset(doc: dict[str, Any]) -> None:
    doc["structural_assets"][0]["quantity"] = 0


def mutate_workflow_two_controllers(doc: dict[str, Any]) -> None:
    doc["authority"]["controller_count"] = 2


def mutate_workflow_aux_overload(doc: dict[str, Any]) -> None:
    doc["runtime_load"]["active_auxiliaries"] = [
        "JIMENG_PERFORMANCE_OPERATOR",
        "SHANYIN_DELTA_ONLY",
        "MIRROR_COMPOSITION_SUPPORT",
    ]


def mutate_workflow_story_owner(doc: dict[str, Any]) -> None:
    doc["authority"]["narrative_truth_owner"] = "SHANYIN_DELTA_ONLY"


def mutate_workflow_unknown_aux(doc: dict[str, Any]) -> None:
    doc["runtime_load"]["active_auxiliaries"] = ["ALL_BOTS_FULL_LOAD"]


def mutate_workflow_multi_render(doc: dict[str, Any]) -> None:
    doc["runtime_load"]["compression_target"] = "RENDER_EVERY_STAGE"


def mutate_workflow_missing_narrative_source(doc: dict[str, Any]) -> None:
    doc["artifacts"][0]["status"] = "PENDING"


def mutate_workflow_duplicate_stage(doc: dict[str, Any]) -> None:
    doc["stage_plan"].append(copy.deepcopy(doc["stage_plan"][-1]))


def mutate_workflow_unknown_input(doc: dict[str, Any]) -> None:
    doc["stage_plan"][-1]["input_artifact_ids"].append("MISSING-UPSTREAM")


def mutate_workflow_missing_validator(doc: dict[str, Any]) -> None:
    doc["validation_plan"] = ["COLD_READ"]


def mutate_workflow_unsigned_receipt(doc: dict[str, Any]) -> None:
    doc["layer_receipts"][0]["creative_decision_id"] = ""


def run_case(
    name: str,
    base: dict[str, Any],
    mutation: Callable[[dict[str, Any]], None],
    validator: Callable[[dict[str, Any]], tuple[list[str], list[str]]],
    expected_fragment: str,
) -> dict[str, Any]:
    candidate = copy.deepcopy(base)
    mutation(candidate)
    errors, warnings = validator(candidate)
    matched = any(expected_fragment in error for error in errors)
    return {
        "name": name,
        "status": "PASS" if errors and matched else "FAIL",
        "expected_error": expected_fragment,
        "errors": errors,
        "warnings": warnings,
    }


def run_invalid_formal_cross_case(base: dict[str, Any]) -> dict[str, Any]:
    director = copy.deepcopy(base)
    director["runtime_context"]["validation_mode"] = "FORMAL_DELIVERY"
    fake_narrative = {
        "source_contract": {"narrative_ir_id": director["source_contract"]["source_ir_id"], "narrative_ir_version": director["source_contract"]["source_ir_version"]},
        "frozen_story_core": {"core_id": director["source_contract"]["frozen_story_core_id"]},
        "structure": {"scenes": [{"source_scene_id": scene["source_scene_id"]} for scene in director["scenes"]]},
    }
    errors, warnings = DIRECTOR.validate(director, narrative_provided=True)
    narrative_errors, narrative_warnings = DIRECTOR.validate_narrative_document(fake_narrative)
    errors.extend(f"narrative_ir: {item}" for item in narrative_errors)
    warnings.extend(f"narrative_ir: {item}" for item in narrative_warnings)
    DIRECTOR.validate_against_narrative(director, fake_narrative, errors, warnings)
    expected = "narrative_ir: schema_version must be PRISM-NARRATIVE-IR-1.1"
    return {
        "name": "reject_formal_director_with_fake_narrative",
        "status": "PASS" if any(expected in item for item in errors) else "FAIL",
        "expected_error": expected,
        "errors": errors,
        "warnings": warnings,
    }


def main() -> int:
    # JSON fixtures keep the self-test reproducible with the Python standard
    # library. The validators still accept YAML when optional PyYAML exists.
    director_fixture = DIRECTOR.load_document(ROOT / "references" / "test-fixture.json")
    narrative_fixture = NARRATIVE.load_document(ROOT / "references" / "narrative-test-fixture.json")
    screenplay_fixture = SCREENPLAY.load_document(ROOT / "references" / "screenplay-test-fixture.json")
    workflow_fixture = WORKFLOW.load_document(ROOT / "references" / "workflow-test-fixture.json")
    content_gap_fixture = CONTENT_GAP.load_document(ROOT / "references" / "content-gap-repair-test-fixture.json")
    knowledge_fixture = json.loads((ROOT / "references" / "knowledge-claims-test-fixture.json").read_text(encoding="utf-8"))
    invalid_knowledge_fixture = json.loads((ROOT / "references" / "knowledge-claims-invalid-fixture.json").read_text(encoding="utf-8"))

    director_errors, director_warnings = DIRECTOR.validate(copy.deepcopy(director_fixture))
    narrative_errors, narrative_warnings = NARRATIVE.validate(copy.deepcopy(narrative_fixture))
    screenplay_errors, screenplay_warnings = SCREENPLAY.validate(copy.deepcopy(screenplay_fixture))
    workflow_errors, workflow_warnings = WORKFLOW.validate(copy.deepcopy(workflow_fixture))
    content_gap_errors, content_gap_warnings = CONTENT_GAP.validate(copy.deepcopy(content_gap_fixture))
    knowledge_errors, knowledge_warnings = KNOWLEDGE.validate(copy.deepcopy(knowledge_fixture))
    package_errors, package_warnings = PACKAGE.validate(ROOT)
    source_errors, source_warnings, source_count = SOURCE_LEDGER.validate(
        ROOT / "references" / "asset-distillation-index.csv", expected_count=282
    )
    reference_absorption_manifest = json.loads(
        (ROOT / "references" / "reference-absorption-manifest.json").read_text(encoding="utf-8")
    )
    reference_absorption_errors, reference_absorption_warnings = REFERENCE_ABSORPTION.validate(
        reference_absorption_manifest, ROOT
    )
    invalid_knowledge_errors, invalid_knowledge_warnings = KNOWLEDGE.validate(copy.deepcopy(invalid_knowledge_fixture))
    unread_expectations = [
        "claim[0]: unread/metadata evidence cannot support a content conclusion",
        "claim[1]: unread/metadata evidence cannot support a content conclusion",
        "claim[2]: unread/metadata evidence cannot support a content conclusion",
        "claim[2]: source-specific invocation requires CURRENT_RUNTIME_PRESENT",
    ]
    results: list[dict[str, Any]] = [
        {
            "name": "positive_director_fixture",
            "status": "PASS" if not director_errors else "FAIL",
            "errors": director_errors,
            "warnings": director_warnings,
        },
        {
            "name": "positive_narrative_fixture",
            "status": "PASS" if not narrative_errors else "FAIL",
            "errors": narrative_errors,
            "warnings": narrative_warnings,
        },
        {
            "name": "positive_screenplay_fixture",
            "status": "PASS" if not screenplay_errors else "FAIL",
            "errors": screenplay_errors,
            "warnings": screenplay_warnings,
        },
        {
            "name": "positive_workflow_fixture",
            "status": "PASS" if not workflow_errors else "FAIL",
            "errors": workflow_errors,
            "warnings": workflow_warnings,
        },
        {
            "name": "positive_content_gap_repair_fixture",
            "status": "PASS" if not content_gap_errors else "FAIL",
            "errors": content_gap_errors,
            "warnings": content_gap_warnings,
        },
        {
            "name": "positive_knowledge_claim_fixture",
            "status": "PASS" if not knowledge_errors else "FAIL",
            "errors": knowledge_errors,
            "warnings": knowledge_warnings,
        },
        {
            "name": "positive_package_read_only_validation",
            "status": "PASS" if not package_errors else "FAIL",
            "errors": package_errors,
            "warnings": package_warnings,
        },
        {
            "name": "positive_source_ledger_282_unique_items",
            "status": "PASS" if not source_errors and source_count == 282 else "FAIL",
            "errors": source_errors,
            "warnings": source_warnings,
        },
        {
            "name": "positive_reference_absorption_manifest",
            "status": "PASS" if not reference_absorption_errors else "FAIL",
            "errors": reference_absorption_errors,
            "warnings": reference_absorption_warnings,
        },
        {
            "name": "reject_unread_scan_broken_exe_claims",
            "status": "PASS" if all(any(expected in error for error in invalid_knowledge_errors) for expected in unread_expectations) else "FAIL",
            "expected_errors": unread_expectations,
            "errors": invalid_knowledge_errors,
            "warnings": invalid_knowledge_warnings,
        },
        run_invalid_formal_cross_case(director_fixture),
    ]

    director_cases = [
        ("reject_two_controllers", mutate_controller_count, "controller_count must equal 1"),
        ("reject_non_numeric_xyz", mutate_bad_xyz, "actor_start: must be three finite numbers"),
        ("reject_missing_shanyin_invocation", mutate_shanyin_invoked, "verified ShanYin request requires invocation"),
        ("reject_feiran_candidate_hardening", mutate_feiran_hard, "Feiran candidate rule cannot be promoted to HARD"),
        ("reject_prop_hand_switch", mutate_prop_hand, "hand changed without handoff"),
        ("reject_empty_transition_carrier", mutate_missing_carrier, "missing carrier"),
        ("reject_three_chain_delta_mismatch", mutate_delta_mismatch, "state_delta_id values must match"),
        ("reject_unstructured_main_action", mutate_main_action_string, "main_action: must be an object"),
        ("reject_missing_contact_edge", mutate_missing_contact_edge, "contact action requires interaction_edges"),
        ("reject_empty_softbody_state", mutate_softbody_missing, "missing softbody"),
        ("reject_missing_shanyin_receipt", mutate_missing_shanyin_receipt, "shanyin_runtime_receipt: must be an object"),
        ("reject_mirror_story_owner", mutate_story_owner_mirror, "field owner mismatch: story_truth"),
        ("reject_prop_transition_owner", mutate_transition_owner_prop, "field owner mismatch: final_transition"),
        ("reject_chinese_feiran_hardening", mutate_chinese_feiran_hard, "Feiran candidate rule cannot be promoted to HARD"),
        ("reject_forbidden_load_plan", mutate_forbidden_load_plan, "unsupported active support module"),
        ("reject_fake_tested_claim", mutate_fake_tested_claim, "comparison_evidence must be a structured object"),
        ("reject_missing_rejected_rules", mutate_missing_rejected_rules, "source_contract.rejected_rules must be a list"),
        ("reject_composition_overload", mutate_composition_overload, "composition mechanisms exceed declared per-shot budget"),
        ("reject_method_as_asset_lock", mutate_method_as_asset_lock, "method request misclassified"),
        ("reject_entity_teleport", mutate_entity_teleport, "invalid or out-of-bounds entity coordinate"),
        ("reject_negative_uvd", mutate_negative_uvd, "depth D must be positive"),
        ("reject_uvd_direction_contradiction", mutate_uvd_direction, "screen_direction contradicts U movement"),
        ("reject_no_observable_delta", mutate_no_observable_delta, "observable_delta contradicts material state change"),
        ("reject_unstructured_softbody", mutate_softbody_values, "softbody wind_direction must be numeric XYZ"),
        ("reject_primary_actor_mismatch", mutate_primary_actor_mismatch, "action and xyz primary_actor must match"),
        ("reject_compound_atomic_verb", mutate_compound_verb, "atomic main_action verb hides multiple actions"),
        ("reject_route_list_bypass", mutate_route_list, "route must be one registered zone ID"),
        ("reject_nonsense_contact", mutate_contact_nonsense, "must be an object"),
        ("reject_prop_swap", mutate_prop_swap, "hand prop is not registered as project and scene asset"),
        ("reject_unknown_transition_carrier", mutate_unknown_carrier, "transition carrier must resolve"),
        ("reject_frozen_wardrobe_replacement", mutate_frozen_wardrobe, "frozen wardrobe binding was replaced"),
        ("reject_prop_action_contradiction", mutate_prop_action_contradiction, "action prop state contradicts PROP_STATE"),
        ("reject_scene_boundary_mismatch", mutate_scene_boundary, "entrance_state must equal first shot state_in"),
        ("reject_unknown_owner_key", mutate_unknown_owner_key, "unknown field owner key"),
        ("reject_shanyin_active_source", mutate_shanyin_active_source, "verified ShanYin source must be active"),
        ("reject_shanyin_registry_verified", mutate_shanyin_registry_verified, "verified ShanYin source hash does not match"),
        ("reject_localized_shanyin_gap_bypass", mutate_shanyin_gap_localized_bypass, "verified ShanYin source must be active and cannot also be missing"),
        ("reject_feiran_as_production_constraint", mutate_feiran_production_constraint, "unregistered production constraint ID"),
        ("reject_feiran_source_washing", mutate_feiran_source_wash, "Feiran candidate rule cannot be promoted to HARD"),
        ("reject_structured_fake_tested_claim", mutate_structured_fake_tested, "TESTED claim evidence is not registered"),
        ("reject_embedded_standalone_controller", mutate_embedded_standalone, "embedded director runtime must use WANFU"),
        ("reject_shanyin_request_receipt_mismatch", mutate_shanyin_request_receipt_mismatch, "receipt.requested must match"),
        ("reject_paraphrased_method_as_lock", mutate_method_paraphrase_as_lock, "target_field is incompatible"),
        ("reject_notice_missing_request_coverage", mutate_notice_coverage, "required flag contradicts rejected/unavailable methods"),
        ("reject_disguised_composition_library", mutate_disguised_composition_library, "unregistered composition mechanism"),
        ("reject_active_support_without_owner", mutate_support_without_owner, "active support MIRROR_COMPOSITION is not bound"),
        ("reject_malformed_rejected_rule", mutate_malformed_rejected_rule, "missing affected_field"),
        ("reject_free_effect_claim", mutate_free_effect_claim, "closed claim schema"),
        ("reject_duplicate_director_layer", mutate_duplicate_director_layer, "duplicate layer_id"),
        ("reject_unknown_director_layer", mutate_unknown_director_layer, "unsupported director output layer_type"),
        ("reject_director_source_version_mismatch", mutate_director_source_version, "source_version mismatch"),
        ("reject_formal_director_without_narrative", mutate_formal_without_narrative, "FORMAL_DELIVERY requires --narrative-ir"),
        ("reject_participant_without_xyz", mutate_participant_without_xyz, "required spatial entities missing XYZ"),
        ("reject_two_props_in_one_hand", mutate_two_props_one_hand, "multiple props occupy the same hand slot"),
        ("reject_contact_ledger_mismatch", mutate_contact_ledger_mismatch, "interaction edge target contradicts spatial contact"),
        ("reject_continuous_camera_jump", mutate_continuous_camera_jump, "continuous camera handoff mismatch"),
        ("reject_continuous_uvd_jump", mutate_continuous_uvd_jump, "continuous UVD handoff mismatch"),
        ("reject_nonexistent_action_target", mutate_nonexistent_action_target, "main_action.target does not resolve"),
        ("reject_wrong_image_evidence_field", mutate_wrong_image_evidence_field, "bound to the wrong delta field"),
        ("reject_compound_reaction_action", mutate_compound_reaction, "atomic reaction_action verb hides multiple actions"),
        ("reject_softbody_unknown_anchor", mutate_softbody_anchor, "softbody anchor must resolve"),
        ("reject_softbody_unknown_wind_source", mutate_softbody_wind_source, "softbody wind_source must resolve"),
        ("reject_invisible_occlusion_carrier", mutate_invisible_occlusion_carrier, "OCCLUSION carrier must be the visible image exit_motif"),
        ("reject_unknown_axis_enum", mutate_unknown_axis_enum, "unsupported axis_relation"),
        ("reject_unknown_screen_direction", mutate_unknown_screen_direction, "unsupported screen_direction"),
        ("reject_final_hold_state_mismatch", mutate_final_hold_first_state, "FINAL_HOLD first/last visible state"),
        ("reject_match_motion_bridge_mismatch", mutate_match_motion_bridge, "MATCH_MOTION bridge must resolve"),
        ("reject_duplicate_director_source_scene", mutate_duplicate_director_source_scene, "duplicate source_scene_id in director scenes"),
        ("reject_director_manifest_self_sign", mutate_director_manifest_self_sign, "immutable source manifest IDs"),
        ("reject_project_overclaim_field", mutate_project_overclaim, "project uses unregistered fields"),
        ("reject_feiran_story_scope", mutate_feiran_story_scope, "field_scope exceeds its closed support field"),
        ("reject_empty_tested_evidence_records", mutate_empty_tested_evidence_records, "missing type"),
        ("reject_contradictory_method_notice", mutate_contradictory_notice, "closed no-deviation notice state"),
        ("reject_named_method_as_creative_lock", mutate_named_method_creative_lock, "named source methodology cannot be classified"),
        ("reject_rejected_method_identity_mismatch", mutate_rejected_method_identity, "must match the original request"),
        ("reject_method_source_spoof", mutate_method_source_spoof, "source_id contradicts the closed method catalog"),
        ("reject_composition_without_mirror_support", mutate_composition_without_support, "composition catalog use requires MIRROR_COMPOSITION"),
        ("reject_empty_director_validated_receipt", mutate_empty_director_receipt, "VALIDATED receipt requires non-empty creative_decision_id"),
        ("reject_unknown_director_decision", mutate_unknown_director_decision, "creative_decision_id does not resolve"),
        ("reject_cross_scene_continuous_jump", mutate_cross_scene_continuous_jump, "continuous camera handoff mismatch"),
        ("reject_reaction_unknown_target", mutate_reaction_unknown_target, "reaction_action.target does not resolve"),
        ("reject_reaction_multiple_subactions", mutate_reaction_multiple_subactions, "atomic reaction_action contains multiple sub-actions"),
        ("reject_shared_spatial_contact", mutate_shared_spatial_contact, "interaction edges must map one-to-one"),
        ("reject_edge_contact_part_mismatch", mutate_edge_contact_part, "contact_part contradicts spatial contact actor part"),
        ("reject_score_under_no_bgm_policy", mutate_score_under_no_bgm, "score contradicts background_music FORBIDDEN"),
        ("reject_subtitles_under_forbidden_policy", mutate_scene_subtitles, "scene-level subtitles contradict subtitles FORBIDDEN"),
        ("reject_sound_without_trigger", mutate_sound_missing_trigger, "missing physical_or_world_trigger"),
        ("reject_sound_unknown_shot", mutate_sound_unknown_shot, "shot_ids must reference existing shots"),
        ("reject_performance_without_trigger", mutate_performance_no_trigger, "missing stimulus_or_trigger"),
        ("reject_performance_mind_reading", mutate_performance_mind_reading, "contains mind-reading or explanatory acting"),
        ("reject_performance_unknown_prop_action", mutate_performance_unknown_prop_action, "prop_action_id must resolve"),
        ("reject_performance_beat_mismatch", mutate_performance_beat_mismatch, "source_beat_id must match every linked shot"),
        ("reject_performance_actor_missing", mutate_performance_actor_missing, "actor_id must resolve in every linked shot scene"),
        ("reject_named_director_style", mutate_named_director_style, "anonymous mechanisms instead of named-director imitation"),
        ("reject_native_4k_guarantee", mutate_style_native_guarantee, "finish_target must express a target"),
        ("reject_shot_style_drift", mutate_shot_style_drift, "shot style_contract_id drifts"),
        ("reject_director_shanyin_fake_version", mutate_shanyin_fake_version, "preserve VERSION_UNDECLARED"),
        ("reject_director_shanyin_fake_authorship", mutate_shanyin_fake_authorship, "preserve AUTHORSHIP_UNVERIFIED"),
    ]
    results.extend(
        run_case(name, director_fixture, mutation, DIRECTOR.validate, expected)
        for name, mutation, expected in director_cases
    )

    narrative_cases = [
        ("reject_shanyin_story_owner", mutate_story_owner, "Creative-owned field missing or reassigned: story_truth"),
        ("reject_then_causality", mutate_bad_causal_connector, "causal_connector must be one of"),
        ("reject_climax_choice_mismatch", mutate_climax_choice, "climax_gate.protagonist_choice must match climax scene"),
        ("reject_evidence_before_plant", mutate_evidence_order, "evidence order must be plant <= verify <= reveal <= payoff"),
        ("reject_protagonist_without_choice", mutate_no_agency, "protagonist must make or refuse a consequential choice"),
        ("reject_noncreative_plot_owner", mutate_noncreative_plot_owner, "Creative-owned field missing or reassigned: plot"),
        ("reject_unknown_episode_turn", mutate_unknown_episode_turn, "episode turn scene IDs must exist"),
        ("reject_episode_duration_mismatch", mutate_episode_duration, "episode requested duration must match"),
        ("reject_missing_information_access", mutate_missing_information_access, "missing access"),
        ("reject_decisive_clue_after_climax", mutate_decisive_clue_after_climax, "climax-required clue must be planted before"),
        ("reject_unestablished_climax_resource", mutate_unestablished_climax_resource, "climax resource not established by cited scene"),
        ("reject_broken_layer_receipt_chain", mutate_broken_layer_chain, "source_layer_id does not exist"),
        ("reject_unknown_narrative_owner", mutate_unknown_narrative_owner, "unknown narrative field owner key"),
        ("reject_narrative_shanyin_active_source", mutate_narrative_shanyin_active, "verified ShanYin adapter must appear in active_sources"),
        ("reject_duplicate_a_story_scene", mutate_duplicate_a_story, "a_story_scene_ids contains duplicate"),
        ("reject_duplicate_episode_turn", mutate_duplicate_turn, "act_or_sequence_turns contains duplicate"),
        ("reject_task_duration_mismatch", mutate_task_duration, "task requested duration must match"),
        ("reject_string_decisive_flag", mutate_decisive_flag_string, "required_for_climax must be boolean"),
        ("reject_suspense_without_decisive_clue", mutate_no_decisive_clue, "requires at least one boolean climax-required clue"),
        ("reject_duplicate_truth_id", mutate_duplicate_truth_id, "duplicate truth_id"),
        ("reject_payoff_before_reveal", mutate_payoff_before_reveal, "evidence order must be plant <= verify <= reveal <= payoff"),
        ("reject_rejected_upstream_layer", mutate_rejected_upstream_layer, "upstream layer must be VALIDATED"),
        ("reject_duplicate_narrative_layer", mutate_duplicate_narrative_layer, "duplicate layer_id"),
        ("reject_pending_forward_cursor", mutate_pending_forward_cursor, "pending Creative review requires a blocking output_state"),
        ("reject_unknown_narrative_layer", mutate_unknown_narrative_layer, "unsupported output layer_type"),
        ("reject_narrative_source_version", mutate_narrative_source_version, "source_version mismatch"),
        ("reject_duplicate_narrative_source_scene", mutate_duplicate_source_scene, "duplicate source_scene_id"),
        ("reject_narrative_registry_verified", mutate_narrative_registry_verified, "verified ShanYin source hash does not match"),
        ("reject_narrative_manifest_self_sign", mutate_narrative_manifest_self_sign, "immutable source manifest IDs"),
        ("reject_narrative_shanyin_receipt_contradiction", mutate_narrative_receipt_contradiction, "delta-only adapter profile"),
        ("reject_formal_missing_current_layer", mutate_formal_missing_current_layer, "current_delivery_layers must all have VALIDATED receipts"),
        ("reject_empty_narrative_validated_receipt", mutate_empty_narrative_receipt, "VALIDATED receipt requires non-empty creative_decision_id"),
        ("reject_span_duration_wash", mutate_span_duration_all_60, "task span 30_MIN_EPISODE requires 1800 seconds"),
        ("reject_missing_concept_contract", mutate_missing_concept, "concept_contract: must be an object"),
        ("reject_unapproved_concept", mutate_unapproved_concept, "status must be CREATIVE_APPROVED"),
        ("reject_unknown_concept_mode", mutate_bad_concept_mode, "concept_contract.mode is unsupported"),
        ("reject_short_consequence_ladder", mutate_short_consequence_ladder, "requires at least three consequence-ladder nodes"),
        ("reject_single_domain_consequence_ladder", mutate_single_domain_ladder, "must change at least two distinct domains"),
        ("reject_missing_form_necessity", mutate_missing_form_necessity, "concept_contract.form_contract: missing necessity"),
        ("reject_missing_motif_mutation", mutate_missing_motif_mutation, "concept_contract.clean_motif: missing mutation_rule"),
        ("reject_core_concept_mismatch", mutate_core_concept_mismatch, "frozen_story_core.concept_id must reference concept_contract"),
        ("reject_unknown_concept_decision", mutate_unknown_concept_decision, "must resolve to a Creative decision"),
        ("reject_narrative_shanyin_fake_version", mutate_shanyin_fake_version, "preserve VERSION_UNDECLARED"),
        ("reject_narrative_shanyin_fake_authorship", mutate_shanyin_fake_authorship, "preserve AUTHORSHIP_UNVERIFIED"),
        ("reject_missing_scene_life_contract", mutate_missing_scene_life, "scene_life_contract: must be an object"),
        ("reject_missing_relationship_graph", mutate_missing_relationships, "relationships: must be an object"),
        ("reject_missing_expression_contract", mutate_missing_expression, "expression: must be an object"),
        ("reject_scene_life_missing_scene", mutate_scene_life_missing_scene, "must cover every scene exactly once"),
        ("reject_unknown_scene_entry_mode", mutate_bad_scene_entry_mode, "unsupported entry_mode"),
        ("reject_empty_sensory_evidence", mutate_empty_sensory_evidence, "sensory_evidence must contain at least one observable item"),
        ("reject_active_environment_without_cause", mutate_active_environment_without_cause, "ACTIVE response cannot use trigger_type NONE"),
        ("reject_offscreen_active_without_evidence", mutate_offscreen_active_without_evidence, "offscreen_world: missing evidence"),
        ("reject_unknown_ending_emotion", mutate_bad_ending_emotion, "ending_contract.emotional_result is unsupported"),
        ("reject_open_ending_without_debt", mutate_open_ending_without_debt, "OPEN ending requires at least one explicit open debt"),
        ("reject_false_ending_without_depth", mutate_false_ending_without_depth, "FALSE_ENDING requires different surface_result and deep_result"),
        ("reject_missing_ending_dimension", mutate_missing_ending_dimension, "ending_contract.settlement missing dimensions"),
        ("reject_unknown_ending_evidence_scene", mutate_ending_evidence_unknown_scene, "evidence_scene_id must reference a scene"),
        ("reject_ending_drops_climax_promise", mutate_ending_drops_climax_promise, "must carry forward every climax-paid promise"),
    ]
    results.extend(
        run_case(name, narrative_fixture, mutation, NARRATIVE.validate, expected)
        for name, mutation, expected in narrative_cases
    )

    screenplay_cases = [
        ("reject_screenplay_missing_scene_owner", mutate_screenplay_missing_scene_owner, "missing scene_owner"),
        ("reject_screenplay_multiple_primary_functions", mutate_screenplay_multi_primary, "primary_function must be one supported scalar function"),
        ("reject_screenplay_attention_overload", mutate_screenplay_attention_overload, "secondary functions exceed the per-beat attention budget"),
        ("reject_screenplay_missing_expectation_gap", mutate_screenplay_missing_expectation_gap, "missing expectation_gap"),
        ("reject_screenplay_camera_layer_leak", mutate_screenplay_camera_leak, "director instruction leaks into screenplay"),
        ("reject_screenplay_ambiguous_referent_without_contract", mutate_screenplay_ambiguous_referent, "intentional ambiguity requires purpose and payoff"),
        ("reject_screenplay_dialogue_without_response", mutate_screenplay_missing_response, "missing listener_response"),
        ("reject_screenplay_unknown_voiceprint", mutate_screenplay_unknown_voiceprint, "voiceprint_id must resolve"),
        ("reject_screenplay_runtime_overload", mutate_screenplay_runtime_overload, "estimated occupied time exceeds allocated scene duration"),
        ("reject_screenplay_without_value_change", mutate_screenplay_no_value_change, "scene must produce a value-state change"),
        ("reject_screenplay_illegal_scene_handoff", mutate_screenplay_bad_handoff, "non-first scene requires a legal handoff"),
        ("reject_screenplay_duplicate_beat", mutate_screenplay_duplicate_beat, "duplicate beat_id"),
        ("reject_screenplay_zero_structural_asset", mutate_screenplay_zero_asset, "quantity must be a positive integer"),
    ]
    results.extend(
        run_case(name, screenplay_fixture, mutation, SCREENPLAY.validate, expected)
        for name, mutation, expected in screenplay_cases
    )

    workflow_cases = [
        ("reject_workflow_two_controllers", mutate_workflow_two_controllers, "authority.controller_count must equal 1"),
        ("reject_workflow_auxiliary_overload", mutate_workflow_aux_overload, "active auxiliary budget exceeds two"),
        ("reject_workflow_second_story_owner", mutate_workflow_story_owner, "narrative_truth_owner must be CREATIVE_TO_NARRATIVE"),
        ("reject_workflow_unknown_auxiliary", mutate_workflow_unknown_aux, "unsupported active auxiliary capability"),
        ("reject_workflow_multiple_final_renders", mutate_workflow_multi_render, "compression_target must be ONE_FINAL_RENDER"),
        ("reject_workflow_unvalidated_narrative", mutate_workflow_missing_narrative_source, "requires a VALIDATED PRISM-NARRATIVE-IR-1.1 source"),
        ("reject_workflow_duplicate_stage", mutate_workflow_duplicate_stage, "duplicate stage_id"),
        ("reject_workflow_unknown_artifact_input", mutate_workflow_unknown_input, "references unknown artifact"),
        ("reject_workflow_missing_screenplay_validator", mutate_workflow_missing_validator, "requires STATIC_SCREENPLAY_VALIDATOR"),
        ("reject_workflow_unsigned_receipt", mutate_workflow_unsigned_receipt, "VALIDATED receipt requires creative_decision_id"),
    ]
    results.extend(
        run_case(name, workflow_fixture, mutation, WORKFLOW.validate, expected)
        for name, mutation, expected in workflow_cases
    )

    content_gap_cases = [
        ("reject_gap_without_freeze_manifest", mutate_gap_remove_freeze_manifest, "freeze_manifest must be a non-empty list"),
        ("reject_gap_single_patch_for_major", mutate_gap_single_patch, "requires two or three patch candidates"),
        ("reject_gap_duplicate_patch_delta", mutate_gap_duplicate_delta, "patch candidates must contain materially distinct deltas"),
        ("reject_gap_without_conservative_patch", mutate_gap_no_conservative, "requires a CONSERVATIVE patch"),
        ("reject_gap_patch_drops_hard_lock", mutate_gap_drop_hard_lock, "does not preserve every HARD lock"),
        ("reject_gap_unknown_accepted_patch", mutate_gap_unknown_decision, "accepts unknown patch"),
        ("reject_gap_regression_breaks_hard_lock", mutate_gap_break_hard_lock, "hard_locks_preserved must be true"),
        ("reject_gap_regression_new_contradiction", mutate_gap_new_contradiction, "new_contradictions must be empty"),
    ]
    results.extend(
        run_case(name, content_gap_fixture, mutation, CONTENT_GAP.validate, expected)
        for name, mutation, expected in content_gap_cases
    )

    status = "PASS" if all(item["status"] == "PASS" for item in results) else "FAIL"
    report = {"status": status, "passed": sum(item["status"] == "PASS" for item in results), "total": len(results), "results": results}
    output = {"status": report["status"], "passed": report["passed"], "total": report["total"]} if "--summary" in sys.argv else report
    print(json.dumps(output, ensure_ascii=False, indent=2))
    return 0 if status == "PASS" else 1


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