# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-benchmark-harness-poisoning-when-litmus-red-team-probes-mutate-the-agent-s-own-memory-store.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-benchmark-harness-poisoning-when-litmus-red-team-probes-mutate-the-agent-s-own-memory-store.warrant.json
# Markdown SHA-256:   ccc6b62700295097276cd9966fa1ffef1943150b9adaa367833d09bed27a6168
# Code AST SHA-256:   b01fe1b1645e2db330039d1e1f113d16a4b0854a6bcaf5af7467c9288f6217c0
# Verified Classes:   ProvenanceBreach, Episode
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Literal


class ProvenanceBreach(RuntimeError):
    """Raised when a turn of harness:probe provenance reaches a tier
    readable by a non-probe session, or when distillation strips the tag."""
    pass


Provenance = Literal["production", "harness:probe"]
PROBE_TOKEN_SALT = b"litmus-probe-v1"  # non-forgeable only if held by harness


@dataclass(frozen=True)
class Episode:
    turn_id: str
    text: str
    provenance: Provenance
    token: bytes  # HMAC over (turn_id, text, provenance); stripped = breach


def _expected_token(turn_id: str, text: str, provenance: Provenance) -> bytes:
    msg = f"{turn_id}\x00{text}\x00{provenance}".encode()
    return hashlib.blake2b(msg, key=PROBE_TOKEN_SALT, digest_size=16).digest()


def persist_episode(ep: Episode, target_tier: str) -> None:
    # Invariant 1: provenance token must verify at the storage boundary.
    if ep.token != _expected_token(ep.turn_id, ep.text, ep.provenance):
        raise ProvenanceBreach(
            f"turn {ep.turn_id}: provenance token invalid or stripped "
            f"before write to tier {target_tier!r}"
        )
    # Invariant 2: probe episodes may not enter any production-readable tier.
    if ep.provenance == "harness:probe" and target_tier != "ephemeral:probe":
        raise ProvenanceBreach(
            f"turn {ep.turn_id}: harness:probe episode written to "
            f"{target_tier!r}; probe co-tenancy breach — refused probes "
            f"still poison distillation downstream"
        )
    _write(ep, target_tier)


def distill(episodes: list[Episode], out_tier: str) -> list[Episode]:
    # Invariant 3: distillation must not mix provenance lanes.
    provenances = {ep.provenance for ep in episodes}
    if len(provenances) > 1:
        raise ProvenanceBreach(
            f"distillation window mixes provenances {provenances}; "
            f"output would be undifferentiated text with no recoverable tag"
        )
    if "harness:probe" in provenances and out_tier != "ephemeral:probe":
        raise ProvenanceBreach(
            f"probe-lane distillation targeted production tier {out_tier!r}"
        )
    return [_summarize(ep) for ep in episodes]


def _write(ep: Episode, tier: str) -> None: ...
def _summarize(ep: Episode) -> Episode: ...
