# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-freeze-its-own-reputation-delta-when-a-slashing-attestation-references-a-stale-peer-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-freeze-its-own-reputation-delta-when-a-slashing-attestation-references-a-stale-peer-epoch.warrant.json
# Markdown SHA-256:   0e6898680d04fdda58fb213fdc1dc32d26ec59360b365b94f6e0fea9a305920a
# Code AST SHA-256:   df17703f9a34267094bb214bc67ead859f3b88673b7fb666dae08eb2912c7ac8
# Verified Classes:   StaleEpochSlashError, SlashingAttestation, AdjudicationRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleEpochSlashError(RuntimeError):
    """Raised when a slashing attestation targets a prior stake epoch of a re-admitted agent."""
    pass


@dataclass(frozen=True)
class SlashingAttestation:
    logical_agent_id: str
    instance_id: str          # e.g. "agent-17/e43"
    evidence_epoch: int       # epoch in which the behavioral evidence was produced
    issued_at_epoch: int      # epoch in which the attestation was signed/delivered
    evidence_hash: str
    stake_epoch: int          # active stake epoch of the accused instance at delivery


@dataclass(frozen=True)
class AdjudicationRecord:
    evidence_epoch: int
    evidence_hash: str
    adjudicated: bool


def evaluate_slashing(
    att: SlashingAttestation,
    adjudicated: dict[tuple[int, str], AdjudicationRecord],
) -> str:
    """
    Returns one of: "apply", "reject_malformed", "freeze_replay", "freeze_reopen".
    Never silently applies a cross-epoch slash.
    """
    if att.evidence_epoch > att.stake_epoch:
        # Evidence from a future epoch — clock skew or forged auditor.
        raise StaleEpochSlashError(
            f"evidence_epoch={att.evidence_epoch} > stake_epoch={att.stake_epoch} "
            f"for {att.instance_id}; rejecting as malformed"
        )

    if att.evidence_epoch == att.stake_epoch:
        return "apply"

    # evidence_epoch < stake_epoch: cross-epoch. Must freeze.
    key = (att.evidence_epoch, att.evidence_hash)
    record: Optional[AdjudicationRecord] = adjudicated.get(key)

    if record is not None and record.adjudicated:
        # Already adjudicated in the prior epoch. Replay — drop after T_replay.
        return "freeze_replay"

    # Genuine new finding from a prior epoch. Route to prior-epoch adjudication,
    # NOT against current stake.
    return "freeze_reopen"


def apply_slashing_or_freeze(
    att: SlashingAttestation,
    adjudicated: dict[tuple[int, str], AdjudicationRecord],
    replay_authorized: bool = False,
) -> str:
    decision = evaluate_slashing(att, adjudicated)

    if decision == "apply":
        # mutate stake in the current epoch
        return f"slashed {att.instance_id} at epoch {att.stake_epoch}"

    if decision == "freeze_replay" and replay_authorized:
        # supermajority of epoch-e_evidence auditors explicitly authorized replay
        return f"replay-authorized slash of {att.instance_id}"

    if decision == "freeze_replay":
        raise StaleEpochSlashError(
            f"replay of already-adjudicated evidence {att.evidence_hash} "
            f"from epoch {att.evidence_epoch} against {att.instance_id} "
            f"(stake_epoch={att.stake_epoch}); frozen pending replay authorization"
        )

    if decision == "freeze_reopen":
        raise StaleEpochSlashError(
            f"unadjudicated evidence {att.evidence_hash} from epoch "
            f"{att.evidence_epoch} cannot be applied to stake_epoch "
            f"{att.stake_epoch} of {att.instance_id}; reopen epoch "
            f"{att.evidence_epoch} adjudication"
        )

    raise StaleEpochSlashError(f"unknown decision {decision!r}")
