# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bind-the-oauth-subject-to-the-a2a-capability-warrant-before-token-exchange-or-the-handoff-silently-impersonates-the-caller.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bind-the-oauth-subject-to-the-a2a-capability-warrant-before-token-exchange-or-the-handoff-silently-impersonates-the-caller.warrant.json
# Markdown SHA-256:   61697aec748fb207888432b4dffa7fbee0e3e42da16b9f79de42f13321d910f8
# Code AST SHA-256:   53fdeb09cf18730323f74f2e8e484241abbdd87a42a271a5c8e7ddfe39903e0a
# Verified Classes:   WarrantScopeViolation, Claim
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class WarrantScopeViolation(RuntimeError):
    """Raised when an exchanged token's derived warrant exceeds the delegating subject's authority."""


@dataclass(frozen=True)
class Claim:
    sub: str
    client_id: str
    scopes: frozenset[str]
    act_chain: tuple[str, ...]  # outermost delegator first, e.g. ("agent:A", "agent:B")


def derive_warrant(inbound: Claim, exchanged: Claim, callee_manifest: frozenset[str]) -> frozenset[str]:
    # Invariant 3: subject immutability across exchange.
    if exchanged.sub != inbound.sub:
        raise WarrantScopeViolation(
            f"subject substituted during exchange: inbound sub={inbound.sub!r} "
            f"exchanged sub={exchanged.sub!r}; cannot bind warrant to a different principal"
        )

    # Invariant 2: delegation chain must be a strict extension, not a rewrite.
    if exchanged.act_chain[: len(inbound.act_chain)] != inbound.act_chain:
        raise WarrantScopeViolation(
            f"delegation chain severed: inbound act={inbound.act_chain} "
            f"exchanged act={exchanged.act_chain}; callee dropped a delegator"
        )

    # Invariant 1: effective scope is the intersection, never the manifest alone.
    effective = inbound.scopes & exchanged.scopes & callee_manifest
    if not effective:
        raise WarrantScopeViolation(
            f"empty warrant: inbound={sorted(inbound.scopes)} exchanged={sorted(exchanged.scopes)} "
            f"manifest={sorted(callee_manifest)}; refusing to fall back to callee manifest"
        )

    # Explicit superset check: the exchanged token must not carry scopes the
    # delegating subject never held. This is the exact condition that produced
    # the admin:audit laundering in the observed incident.
    over_broad = exchanged.scopes - inbound.scopes
    if over_broad:
        raise WarrantScopeViolation(
            f"exchanged token exceeds delegating scope: {sorted(over_broad)} "
            f"not present in inbound scopes {sorted(inbound.scopes)}"
        )

    return effective


def handle_handoff(inbound: Claim, exchanged: Claim, callee_manifest: frozenset[str]) -> frozenset[str]:
    try:
        return derive_warrant(inbound, exchanged, callee_manifest)
    except WarrantScopeViolation:
        # Fail closed before any tool call is dispatched; do not downgrade silently.
        raise
