# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-harness-echo-contamination-when-a-litmus-safety-benchmark-s-adversarial-multi-turn-driver-leaks-the-scoring-rubric-into-th.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-harness-echo-contamination-when-a-litmus-safety-benchmark-s-adversarial-multi-turn-driver-leaks-the-scoring-rubric-into-th.warrant.json
# Markdown SHA-256:   9ad103a80f719502b4f3ec14a732b43127669e4c401488fff65971c323a57ba3
# Code AST SHA-256:   08577faab4de5e27b2bf83eefc08613016c23b820f9ed4cdab3d39319f2d4b33
# Verified Classes:   HarnessEchoContamination
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class HarnessEchoContamination(RuntimeError):
    """Raised when evaluation-domain data leaks into the target's context."""
    pass


EVAL_DOMAIN_PROVENANCE = frozenset({"driver", "judge", "harness_rubric", "ground_truth"})


def assemble_target_context(turn_messages: list[dict], episode_id: str) -> list[dict]:
    """
    Build the target agent's context for one turn, enforcing the
    channel-separation invariant: no evaluation-domain message may
    appear in the target's assembled context.

    Each message is expected to be:
        {"provenance": str, "role": str, "content": str}
    """
    assembled = []
    for msg in turn_messages:
        prov = msg.get("provenance")
        if prov is None:
            raise HarnessEchoContamination(
                f"episode {episode_id}: message missing provenance tag; "
                f"cannot verify channel separation (content head={msg.get('content','')[:60]!r})"
            )
        if prov in EVAL_DOMAIN_PROVENANCE:
            raise HarnessEchoContamination(
                f"episode {episode_id}: evaluation-domain provenance {prov!r} "
                f"reached target context assembler; episode invalid at this turn"
            )
        if prov not in {"target", "user"}:
            raise HarnessEchoContamination(
                f"episode {episode_id}: unrecognized provenance {prov!r}; "
                f"refusing to pass through unverified channel"
            )
        assembled.append(msg)
    return assembled


def score_episode(episode: dict) -> dict:
    """
    Score a single LITMUS episode, but only if every turn's assembled
    context passed the channel-separation invariant. A contaminated
    episode yields no verdict -- not a conservative one.
    """
    episode_id = episode["id"]
    for turn in episode["turns"]:
        try:
            assemble_target_context(turn["messages"], episode_id)
        except HarnessEchoContamination as exc:
            # Do NOT strip and re-score. The target's later turns are
            # already conditioned on having seen the leaked content.
            return {
                "episode_id": episode_id,
                "valid": False,
                "verdict": None,
                "reason": str(exc),
                "coverage_note": "episode excluded from aggregate; re-run from turn 0",
            }
    return {
        "episode_id": episode_id,
        "valid": True,
        "verdict": episode["judge_verdict"],
        "reason": None,
        "coverage_note": None,
    }
