# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-org-capability-attestation-from-silently-downgrading-during-federated-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-org-capability-attestation-from-silently-downgrading-during-federated-handoff.warrant.json
# Markdown SHA-256:   d1db4224735422ecedb0fcce3cb6a0d91a550ebb3e36388a874f4f663f11fa05
# Code AST SHA-256:   1be7ca77dea5c0fe1bb55d548791e799b1011cec1e0af04356e16ab868b87343
# Verified Classes:   CapabilityDowngradeError, Verdict, Attestation, NegotiationResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class CapabilityDowngradeError(RuntimeError):
    """Raised when a federated handoff returns an effective capability set
    that is not equal to the claimed set, and the origin plan did not
    declare the missing capabilities as optional."""
    pass


class Verdict(Enum):
    GRANTED = "granted"
    PARTIAL = "partial"
    DENIED = "denied"


@dataclass(frozen=True)
class Attestation:
    claimed: FrozenSet[str]
    optional: FrozenSet[str] = frozenset()


@dataclass(frozen=True)
class NegotiationResult:
    verdict: Verdict
    granted: FrozenSet[str]
    denied: FrozenSet[str]


def negotiate(att: Attestation, receiver_permits: FrozenSet[str]) -> NegotiationResult:
    """Filter-style negotiation, but emits the diff instead of swallowing it."""
    granted = att.claimed & receiver_permits
    denied = att.claimed - receiver_permits
    if not denied:
        return NegotiationResult(Verdict.GRANTED, granted, frozenset())
    if not granted:
        return NegotiationResult(Verdict.DENIED, frozenset(), denied)
    return NegotiationResult(Verdict.PARTIAL, granted, denied)


def admit_handoff(att: Attestation, result: NegotiationResult) -> None:
    """Enforce equality-or-escalate. The origin — not the receiver — decides
    whether a partial grant is tolerable, based on its own plan shape."""
    if result.verdict is Verdict.GRANTED:
        return
    if result.verdict is Verdict.DENIED:
        raise CapabilityDowngradeError(
            f"handoff denied entirely; missing={sorted(result.denied)}"
        )
    # PARTIAL: only acceptable if every missing capability was declared optional
    unhandled = result.denied - att.optional
    if unhandled:
        raise CapabilityDowngradeError(
            "silent capability downgrade blocked: receiver granted "
            f"{sorted(result.granted)} but origin plan required "
            f"{sorted(unhandled)} which receiver could not attest. "
            "Origin must re-plan or explicitly mark these optional."
        )


# --- trace of the observed failure ---
att = Attestation(
    claimed=frozenset({"read:order", "read:customer_pii", "invoke:refund_api"}),
    optional=frozenset(),  # origin plan treated PII as required
)
p2_permits = frozenset({"read:order", "invoke:refund_api"})  # no PII mapping

result = negotiate(att, p2_permits)
assert result.verdict is Verdict.PARTIAL
assert result.denied == frozenset({"read:customer_pii"})

admit_handoff(att, result)  # raises CapabilityDowngradeError — the fix
