# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-protocol-non-conformance-from-legitimate-capability-degradation-in-agentic-interoperability-certification.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-protocol-non-conformance-from-legitimate-capability-degradation-in-agentic-interoperability-certification.warrant.json
# Markdown SHA-256:   ca7357a8f45d6996438992ebf4311ec66712af9c7c4cac123578e03c330f720b
# Code AST SHA-256:   8adf4e3c62a5a84917fe0db32ca0a326bb564416fc24bc8e04ca1b2cce1eb6c9
# Verified Classes:   Verdict, ConformanceOrderViolation, Message
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class Verdict(Enum):
    CONFORMANT = "conformant"
    NON_CONFORMANT = "non_conformant"


class ConformanceOrderViolation(RuntimeError):
    """Raised when a harness attempts to grade payload before structural/state checks."""


@dataclass
class Message:
    call_id: str | None
    transition: str          # e.g. "tool_call", "tool_result", "refusal"
    payload_ok: bool


LEGAL_TRANSITIONS = {
    ("tool_call", "tool_result"),
    ("tool_call", "refusal"),
    ("refusal", "tool_result"),
}


def certify(messages: list[Message], legal_refusals: set[str]) -> Verdict:
    """Decide conformance strictly on structure + state machine, never on payload."""
    # Step 1: structural invariant -- correlation id required on every message.
    for m in messages:
        if not m.call_id:
            # A correct payload must NOT rescue a missing correlation field.
            return Verdict.NON_CONFORMANT

    # Step 2: state-machine replay against the spec automaton.
    for prev, cur in zip(messages, messages[1:]):
        if (prev.transition, cur.transition) not in LEGAL_TRANSITIONS:
            return Verdict.NON_CONFORMANT

    # A refusal is a legal terminal state; it does not affect conformance.
    for m in messages:
        if m.transition == "refusal" and m.transition not in legal_refusals:
            return Verdict.NON_CONFORMANT

    return Verdict.CONFORMANT


def grade_payload(messages: list[Message], conformance: Verdict) -> bool:
    """Payload grading is a separate capability metric and must run last."""
    if conformance is not Verdict.CONFORMANT:
        raise ConformanceOrderViolation(
            "payload grading attempted on a non-conformant transcript; "
            "capability metrics must never influence the conformance verdict"
        )
    # Only now, and reported independently of conformance:
    return all(m.payload_ok for m in messages)
