# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-policy-negotiation-downgrade-attack-during-cross-org-capability-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-policy-negotiation-downgrade-attack-during-cross-org-capability-delegation.warrant.json
# Markdown SHA-256:   80cc065aa6e72802e8c0b0bd222577bd30612b6832d9a4a6d6455a9ff4a4c097
# Code AST SHA-256:   e45e882eabe0ababafffb05feda4329d3474ba599fd04128bc34c65101a4c2b4
# Verified Classes:   ScopeDowngradeError, Warrant, AdmissionAck
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeDowngradeError(RuntimeError):
    """Raised when a callee's effective grant diverges from the requested warrant scope."""


@dataclass(frozen=True)
class Warrant:
    subject: str
    resource: str
    actions: FrozenSet[str]
    issuer: str


@dataclass(frozen=True)
class AdmissionAck:
    admitted: bool
    effective_scope: FrozenSet[str] | None
    warrant_ref: str


def verify_delegation(warrant: Warrant, ack: AdmissionAck) -> FrozenSet[str]:
    """Return the admitted action set, or raise if the trust boundary was crossed.

    The invariant: effective_scope must equal requested actions as a set.
    Narrowing (downgrade) and widening (escalation) are both violations.
    """
    if not ack.admitted:
        raise ScopeDowngradeError(
            f"delegation refused for warrant {warrant.subject}@{warrant.resource}"
        )
    if ack.effective_scope is None:
        raise ScopeDowngradeError(
            f"callee returned no structured effective_scope for {ack.warrant_ref}; "
            "cannot verify trust boundary — treating as unverified"
        )

    requested = warrant.actions
    effective = ack.effective_scope

    if effective < requested:
        missing = requested - effective
        raise ScopeDowngradeError(
            f"silent downgrade on {ack.warrant_ref}: callee admitted {sorted(effective)} "
            f"but warrant requested {sorted(requested)}; missing={sorted(missing)}"
        )
    if effective > requested:
        extra = effective - requested
        raise ScopeDowngradeError(
            f"scope escalation on {ack.warrant_ref}: callee granted {sorted(extra)} "
            "not present in the warrant — possible compatibility-shim substitution"
        )
    return effective


def handoff(warrant: Warrant, ack: AdmissionAck, task_state: dict) -> None:
    """Commit admitted capability to task state only after boundary verification."""
    admitted = verify_delegation(warrant, ack)
    task_state["granted_actions"] = admitted
    task_state["delegation_verified"] = True
