# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-delegated-credential-scope-inflation-when-an-aaif-warrant-is-re-signed-across-multi-hop-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-delegated-credential-scope-inflation-when-an-aaif-warrant-is-re-signed-across-multi-hop-agent-handoffs.warrant.json
# Markdown SHA-256:   839f2939578b282455f6efda59acf087cc4ca19a2716c11a16412df3d0d7cd4c
# Code AST SHA-256:   3f145a0e161d86472e288a170a6e397ca68816d3d76b2e74de982341116f6a86
# Verified Classes:   AttenuationViolation, Warrant
# Defensive Guards:   10 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AttenuationViolation(RuntimeError):
    """Raised when a delegated warrant chain widens authority relative to its ancestry."""
    pass


@dataclass(frozen=True)
class Warrant:
    scope: frozenset[str]      # e.g. {"repo:read:org/acme/*"}
    expiry: int                # absolute epoch seconds
    audience: frozenset[str]   # agent identities permitted to use it
    parent_hash: Optional[str] # None only for the root
    signature_valid: bool


def effective_bounds(chain: list[Warrant]) -> Warrant:
    """Chain is ordered root-first. Compute the intersection of all ancestors."""
    if not chain:
        raise AttenuationViolation("empty chain: no root to anchor authority")
    root = chain[0]
    if root.parent_hash is not None:
        raise AttenuationViolation("chain does not terminate at a root warrant")
    scope = set(root.scope)
    audience = set(root.audience)
    expiry = root.expiry
    prev = root
    for w in chain[1:]:
        if not w.signature_valid:
            raise AttenuationViolation(f"invalid signature at hop: {w}")
        if w.parent_hash is None:
            raise AttenuationViolation("interior warrant claims to be a root")
        # Disqualifying on its own: any widening hop breaks the integrity model.
        if not w.scope.issubset(prev.scope):
            raise AttenuationViolation(
                f"scope inflation at hop: {w.scope - prev.scope} not in parent"
            )
        if w.expiry > prev.expiry:
            raise AttenuationViolation(
                f"expiry extension at hop: {w.expiry} > parent {prev.expiry}"
            )
        if not w.audience.issubset(prev.audience):
            raise AttenuationViolation(
                f"audience widening at hop: {w.audience - prev.audience}"
            )
        scope &= w.scope
        audience &= w.audience
        expiry = min(expiry, w.expiry)
        prev = w
    return Warrant(
        scope=frozenset(scope),
        expiry=expiry,
        audience=frozenset(audience),
        parent_hash=chain[-1].parent_hash,
        signature_valid=True,
    )


def authorize(chain: list[Warrant], action: str, agent: str, now: int) -> None:
    """Check a request against effective ancestry bounds, never the leaf's claims."""
    eff = effective_bounds(chain)
    if now >= eff.expiry:
        raise AttenuationViolation(f"effective expiry {eff.expiry} passed at {now}")
    if agent not in eff.audience:
        raise AttenuationViolation(f"agent {agent} outside effective audience")
    if action not in eff.scope:
        raise AttenuationViolation(
            f"action {action} outside effective scope {sorted(eff.scope)}"
        )
