# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-negotiated-agent-to-agent-sla-has-silently-degraded-to-a-best-effort-contract-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-negotiated-agent-to-agent-sla-has-silently-degraded-to-a-best-effort-contract-mid-execution.warrant.json
# Markdown SHA-256:   1e6c95b3927fef3f2f06ec64703bbc55903050e9d7ab837178adeb9293ecef23
# Code AST SHA-256:   1e38557ac6b1430e15c070d0c63292a6cc220107bf0baa75abaeddd7003a5332
# Verified Classes:   ContractDriftError, Verdict, Contract, Attestation, CallerMonitor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class ContractDriftError(RuntimeError):
    """Raised when a callee serves under terms weaker than the asserted contract
    without a causally-preceding, hash-bound degradation event."""
    pass


class Verdict(Enum):
    ACCEPT = "accept"
    QUARANTINE = "quarantine"
    RENEGOTIATE = "renegotiate"


@dataclass(frozen=True)
class Contract:
    contract_hash: str
    max_latency_ms: int
    min_fidelity: float
    retry_budget: int
    verification: str


@dataclass(frozen=True)
class Attestation:
    contract_hash: str
    callee_epoch: str
    seq: int
    model_tier: str
    fidelity: float
    verification: str
    retries_used: int
    signature: str  # opaque; assumed verified upstream


@dataclass
class CallerMonitor:
    contract: Contract
    hard_fidelity_floor: float
    last_seq: int = -1
    epoch: str = ""
    pending_degradations: list = field(default_factory=list)

    def _seq_ok(self, att: Attestation) -> bool:
        if att.callee_epoch != self.epoch:
            # Epoch change is a forced renegotiation, never a continuation.
            return False
        return att.seq == self.last_seq + 1

    def judge(self, att: Attestation | None) -> Verdict:
        if att is None:
            return Verdict.QUARANTINE  # no attestation == no evidence
        if att.contract_hash != self.contract.contract_hash:
            raise ContractDriftError(
                f"attestation bound to {att.contract_hash[:8]} but caller asserts "
                f"{self.contract.contract_hash[:8]}"
            )
        if not self._seq_ok(att):
            return Verdict.QUARANTINE  # gap or epoch reset: causality broken
        self.last_seq = att.seq
        self.epoch = att.callee_epoch

        weaker = (
            att.fidelity < self.contract.min_fidelity
            or att.verification != self.contract.verification
            or att.model_tier != "primary"
        )
        if not weaker:
            return Verdict.ACCEPT

        # Weaker terms: legal only if a degradation event preceded this seq.
        has_event = any(
            d["seq"] < att.seq and d["contract_hash"] == self.contract.contract_hash
            for d in self.pending_degradations
        )
        if not has_event:
            raise ContractDriftError(
                f"silent degradation at seq={att.seq}: fidelity={att.fidelity} "
                f"tier={att.model_tier} with no preceding degradation event"
            )
        if att.fidelity < self.hard_fidelity_floor:
            return Verdict.RENEGOTIATE  # below floor: must renegotiate, not accept
        return Verdict.RENEGOTIATE  # above floor but changed: explicit renegotiation


def ingest_degradation_event(monitor: CallerMonitor, event: dict) -> None:
    if event.get("contract_hash") != monitor.contract.contract_hash:
        raise ContractDriftError("degradation event bound to wrong contract")
    monitor.pending_degradations.append(event)
