# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-capability-negotiation-divergence-from-protocol-violation-in-mcp-a2a-conformance-fuzzing.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-capability-negotiation-divergence-from-protocol-violation-in-mcp-a2a-conformance-fuzzing.warrant.json
# Markdown SHA-256:   1c69b2e8e6a241f3a0014977e636adc732264e15ee426bb515a179e3221f4cfa
# Code AST SHA-256:   5bac44ca34d2de32728ea5537eed640eff616610bc51ef56d81a4a1abf1b6392
# Verified Classes:   UndeclaredReachabilityError, Verdict, Baseline, Session
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class UndeclaredReachabilityError(RuntimeError):
    """Raised when a peer responds successfully to a method it never declared.

    This is the high-severity divergence: the real capability surface is wider
    than the declared one, so an attacker can drive code paths the operator
    believed disabled. Distinct from phantom capability (declared-but-absent),
    which is a lower-severity honest-client breakage.
    """


class Verdict(Enum):
    CONFORMANT = "conformant"
    CAPABILITY_DIVERGENCE_PHANTOM = "capability_divergence_phantom"
    PROTOCOL_VIOLATION = "protocol_violation"
    INDETERMINATE = "indeterminate"


@dataclass(frozen=True)
class Baseline:
    protocol_version: str
    declared_methods: frozenset[str]


@dataclass
class Session:
    protocol_version: str
    framing_ok: bool
    method: str
    succeeded: bool
    errored_cleanly: bool


def classify(baseline: Baseline, session: Session) -> Verdict:
    # Step 1: version must match baseline, else the oracle is circular.
    if session.protocol_version != baseline.protocol_version:
        return Verdict.INDETERMINATE

    # Step 2: framing first. Never do semantic analysis on a broken frame.
    if not session.framing_ok:
        return Verdict.PROTOCOL_VIOLATION

    declared = session.method in baseline.declared_methods

    # Step 3: directional semantic comparison against frozen baseline.
    if declared and not session.succeeded:
        return Verdict.CAPABILITY_DIVERGENCE_PHANTOM
    if not declared and session.succeeded:
        raise UndeclaredReachabilityError(
            f"peer returned success for undeclared method {session.method!r} "
            f"under protocol {session.protocol_version!r}; "
            f"declared surface was {sorted(baseline.declared_methods)}"
        )
    if not declared and session.errored_cleanly:
        return Verdict.CONFORMANT
    return Verdict.CONFORMANT


def run_matrix(baseline: Baseline, sessions: list[Session]) -> dict[Verdict, int]:
    tally: dict[Verdict, int] = {v: 0 for v in Verdict}
    for s in sessions:
        tally[classify(baseline, s)] += 1
    return tally
