# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-delegated-a2a-task-s-identity-warrant-was-silently-downgraded-at-a-federation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-delegated-a2a-task-s-identity-warrant-was-silently-downgraded-at-a-federation-boundary.warrant.json
# Markdown SHA-256:   dec924ddc6753144ce655c0bc06ab44d177e69962492c4190428424d63126656
# Code AST SHA-256:   0b21e0aea9762fc096ec3213b4265304054366f5c4a3fd502847f1e1e06d5b75
# Verified Classes:   WarrantChainViolation, Hop
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class WarrantChainViolation(RuntimeError):
    """Raised when a delegated result's exercised scope cannot be verified
    against the originator's intended scope."""
    pass


@dataclass(frozen=True)
class Hop:
    issuer: str
    subject: str
    scope: frozenset[str]
    depth: int
    signed: bool
    binds_parent: bool  # does this token reference the inbound warrant hash?


def verify_delegation_chain(
    intended_scope: frozenset[str],
    chain: Sequence[Hop],
    originator: str,
) -> frozenset[str]:
    """Return the effective (intersected) scope, or raise if the chain is
    broken, unbounded, or silently narrowed."""
    if not chain:
        raise WarrantChainViolation("empty warrant chain: cannot verify exercised scope")

    # Hop 0 must be issued by the originator and bind nothing (it is the root).
    if chain[0].issuer != originator:
        raise WarrantChainViolation(
            f"chain root issuer {chain[0].issuer!r} != originator {originator!r}"
        )

    effective = chain[0].scope
    prev = chain[0]
    for i, hop in enumerate(chain[1:], start=1):
        if not hop.signed:
            raise WarrantChainViolation(f"hop {i} ({hop.issuer}) is unsigned")
        if not hop.binds_parent:
            # Re-issuance without chain binding: the attenuation baseline
            # was reset to the local service identity. This is the exact
            # silent-downgrade condition.
            raise WarrantChainViolation(
                f"hop {i} ({hop.issuer}) does not bind parent warrant; "
                f"scope attenuation cannot be verified"
            )
        if hop.depth < 1:
            raise WarrantChainViolation(f"hop {i} exhausted delegation depth")
        if not hop.scope.issubset(prev.scope):
            # Scope was widened at a boundary — the re-widening failure.
            raise WarrantChainViolation(
                f"hop {i} scope {sorted(hop.scope)} not subset of "
                f"parent {sorted(prev.scope)}: authority re-widened"
            )
        effective = effective & hop.scope
        prev = hop

    if not effective.issubset(intended_scope):
        raise WarrantChainViolation(
            f"exercised scope {sorted(effective)} exceeds intended "
            f"{sorted(intended_scope)}"
        )
    if effective != intended_scope:
        # Degraded but bounded: caller must decide, not silently consume.
        raise WarrantChainViolation(
            f"degraded delegation: exercised {sorted(effective)} "
            f"< intended {sorted(intended_scope)}"
        )
    return effective
