# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-adversarial-litmus-scenario-generators-from-silently-laundering-unsafe-trajectories-into-passing-safety-benchmarks.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-adversarial-litmus-scenario-generators-from-silently-laundering-unsafe-trajectories-into-passing-safety-benchmarks.warrant.json
# Markdown SHA-256:   d48dc120fdf4c6b49d81670369121a6f8ff75163f338d2ddfc02381c52892424
# Code AST SHA-256:   06268eb96f0b30693e0896a04cb67cc930cc065b3a09e55f665117d7771dc4ee
# Verified Classes:   ScenarioLabelDriftError, HazardDescriptor, Scenario
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import dataclasses
from typing import Callable, Any


class ScenarioLabelDriftError(RuntimeError):
    """Raised when a scenario's rubric no longer sandwiches its hazard descriptor."""
    pass


@dataclasses.dataclass(frozen=True)
class HazardDescriptor:
    tool: str
    arg_pattern: str
    target: str
    effect_predicate: Callable[[dict], bool]


@dataclasses.dataclass(frozen=True)
class Scenario:
    scenario_id: str
    descriptor: HazardDescriptor
    rubric: Callable[[list[dict]], str]  # returns "SAFE" | "UNSAFE"


def validate_sandwich(
    scenario: Scenario,
    realize_probe: list[dict],
    benign_touch_probe: list[dict],
) -> None:
    """
    Enforce: realize(hazard) subset-of label_UNSAFE(rubric)
             label_UNSAFE(rubric) subset-of touch(target).

    Both probes must be executed against the scenario's rubric. If the
    realize probe does not label UNSAFE, the rubric has drifted off the
    hazard. If the benign probe labels UNSAFE, the rubric is over-broad.
    """
    d = scenario.descriptor

    if not d.effect_predicate(realize_probe[-1]):
        raise ScenarioLabelDriftError(
            f"scenario {scenario.scenario_id}: realize_probe does not "
            f"realize hazard on tool={d.tool} target={d.target}"
        )

    realize_label = scenario.rubric(realize_probe)
    if realize_label != "UNSAFE":
        raise ScenarioLabelDriftError(
            f"scenario {scenario.scenario_id}: realize_probe labeled "
            f"{realize_label!r}; rubric no longer fires on the hazard. "
            f"Target={d.target} tool={d.tool}. Descriptor/rubric decoupled."
        )

    benign_label = scenario.rubric(benign_touch_probe)
    if benign_label == "UNSAFE":
        raise ScenarioLabelDriftError(
            f"scenario {scenario.scenario_id}: benign_touch_probe labeled "
            f"UNSAFE; rubric over-broad and will flag safe deliberate probing."
        )


def regenerate_scenario(
    old: Scenario,
    mutate: Callable[[Scenario], Scenario],
    build_realize_probe: Callable[[HazardDescriptor], list[dict]],
    build_benign_probe: Callable[[HazardDescriptor], list[dict]],
) -> Scenario:
    """
    Mutate a scenario and atomically revalidate. If the mutation moves the
    hazard target, the descriptor is invalid and the scenario is unscorable
    until a fresh descriptor is supplied and both probes re-run.
    """
    new = mutate(old)

    if new.descriptor.target != old.descriptor.target:
        # target moved: descriptor is stale, must not be scored as-is
        raise ScenarioLabelDriftError(
            f"scenario {new.scenario_id}: mutation moved hazard target "
            f"{old.descriptor.target!r} -> {new.descriptor.target!r}; "
            f"descriptor must be re-derived before scoring."
        )

    validate_sandwich(
        new,
        realize_probe=build_realize_probe(new.descriptor),
        benign_touch_probe=build_benign_probe(new.descriptor),
    )
    return new
