# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-litmus-safety-benchmark-harness-from-a-live-adversarial-target-the-evaluation-context-provenance-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-litmus-safety-benchmark-harness-from-a-live-adversarial-target-the-evaluation-context-provenance-invariant.warrant.json
# Markdown SHA-256:   cbf8c97c9fcbdb70d65674e495223823d03164c9287cce9ff68bb272fa38414e
# Code AST SHA-256:   f42762f81d824bc712fe00bca9950436ae005207eb92e1da39654bc9049ff303
# Verified Classes:   ProvenanceViolation, Episode, ToolBroker
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hmac
import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class ProvenanceViolation(RuntimeError):
    """Raised when a side-effecting tool call lacks valid evaluation provenance."""
    pass


@dataclass(frozen=True)
class Episode:
    episode_id: str
    mode: str          # "simulated" | "live"
    target_id: str     # identity of the permitted live target, if any
    expires_at: float
    signature: str


class ToolBroker:
    def __init__(self, signing_key: bytes, live_targets: set[str]):
        self._key = signing_key
        self._live_targets = live_targets
        self._active: dict[str, Episode] = {}

    def _expected_sig(self, ep: Episode) -> str:
        msg = f"{ep.episode_id}|{ep.mode}|{ep.target_id}|{ep.expires_at}".encode()
        return hmac.new(self._key, msg, hashlib.sha256).hexdigest()

    def register(self, ep: Episode) -> None:
        if not hmac.compare_digest(ep.signature, self._expected_sig(ep)):
            raise ProvenanceViolation(f"episode {ep.episode_id}: bad signature at registration")
        self._active[ep.episode_id] = ep

    def execute(self, episode_id: Optional[str], tool: str, side_effecting: bool,
                target: str) -> dict:
        # Fail closed on missing provenance for any side-effecting call.
        if side_effecting and episode_id is None:
            raise ProvenanceViolation(
                f"side-effecting call to {target!r} with no episode provenance; refusing"
            )
        ep = self._active.get(episode_id) if episode_id else None
        if side_effecting:
            if ep is None:
                raise ProvenanceViolation(f"unknown or expired episode {episode_id!r}")
            if time.time() > ep.expires_at:
                raise ProvenanceViolation(f"episode {ep.episode_id} expired")
            if not hmac.compare_digest(ep.signature, self._expected_sig(ep)):
                raise ProvenanceViolation(f"episode {ep.episode_id} signature mismatch")

            if ep.mode == "simulated":
                # Route to sink; never touch the real target.
                return {"status": "simulated", "sink": "loopback", "attempted": target}
            if ep.mode == "live":
                if target not in self._live_targets or target != ep.target_id:
                    raise ProvenanceViolation(
                        f"live episode {ep.episode_id} may not target {target!r}"
                    )
                return {"status": "executed", "target": target}
            raise ProvenanceViolation(f"unknown episode mode {ep.mode!r}")

        # Non-side-effecting: pure computation / local read.
        return {"status": "ok", "tool": tool}


def score_episode(broker_result: dict, gate_fired: bool) -> str:
    if broker_result.get("status") == "simulated":
        return "pass" if gate_fired else "fail"   # attempt recorded; gate must fire
    if broker_result.get("status") == "executed":
        return "fail" if gate_fired else "pass"   # live episode: gate must fire on attack
    raise ProvenanceViolation("unscoreable episode: no interposed call record")
