# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-pass-the-litmus-safety-harness-in-isolation-but-regress-the-safety-score-once-wired-into-the-continuous-red-team-gate.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-pass-the-litmus-safety-harness-in-isolation-but-regress-the-safety-score-once-wired-into-the-continuous-red-team-gate.warrant.json
# Markdown SHA-256:   b9ac170fa5dfbbd52639c2d625ced1953377cc8c86c56285abd51aad940db0cd
# Code AST SHA-256:   993cfbd166c56ed0c20e17af21d4e4b7f8edbfeb583da0493533340ad21361f4
# Verified Classes:   ProbeIsolationViolation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ProbeIsolationViolation(RuntimeError):
    """Raised when a LITMUS gate run contaminates the MUT context channel."""


ALLOWED_CARRY_FORWARD_CHANNELS = {"user", "tool_result", "retrieved_doc"}
SINGLE_TURN_FAMILIES = {"prompt_injection_indirect", "tool_output_poisoning", "direct_jailbreak"}


def assert_probe_isolation(probe_family: str, channel_trace: list[dict]) -> None:
    """
    channel_trace: ordered list of {channel, origin, tokens} entries describing
    how each piece of context entered the MUT for this probe.
    """
    if not channel_trace:
        raise ProbeIsolationViolation(
            f"probe {probe_family!r}: empty channel trace, harness did not record ingress"
        )

    for entry in channel_trace:
        channel = entry.get("channel")
        origin = entry.get("origin")

        if channel == "assistant" and probe_family in SINGLE_TURN_FAMILIES:
            raise ProbeIsolationViolation(
                f"probe {probe_family!r}: assistant-channel contamination from "
                f"origin={origin!r}; adversarial payload promoted into MUT output channel"
            )

        if channel not in ALLOWED_CARRY_FORWARD_CHANNELS and channel != "system":
            raise ProbeIsolationViolation(
                f"probe {probe_family!r}: unexpected ingress channel {channel!r}"
            )

        if channel == "system" and origin == "red_team_preamble":
            raise ProbeIsolationViolation(
                f"probe {probe_family!r}: evaluation frame leaked into scored context "
                f"via system channel; deliver out-of-band"
            )

        if origin == "judge_annotation":
            raise ProbeIsolationViolation(
                f"probe {probe_family!r}: judge annotation written back into MUT channel "
                f"{channel!r}; judge state must be read-only and isolated"
            )


def gate_probe(probe_family: str, channel_trace: list[dict]) -> str:
    try:
        assert_probe_isolation(probe_family, channel_trace)
    except ProbeIsolationViolation as exc:
        return f"BLOCKED_CONTAMINATED: {exc}"
    return "SCORED"
