# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-an-over-broad-delegated-authorization-scope-inherited-through-aaif-token-exchange-in-an-autonomous-agent-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-an-over-broad-delegated-authorization-scope-inherited-through-aaif-token-exchange-in-an-autonomous-agent-chain.warrant.json
# Markdown SHA-256:   619133ee0f9d6acf239b7e6e7f0b9d79b66dd93d6fc4e5ba34affd2da9808bd7
# Code AST SHA-256:   2be8cbee1d47ef0d1aee2cbd6f861732d7eaf879c5441db2d9170fa694ca5515
# Verified Classes:   ScopeInheritanceViolation, DelegatedToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeInheritanceViolation(RuntimeError):
    """Raised when a delegated token's scope set is not a subset of the
    originating grant's scope set, indicating over-broad inheritance
    through one or more token-exchange hops."""
    pass


@dataclass(frozen=True)
class DelegatedToken:
    subject: str
    scopes: FrozenSet[str]
    parent_subject: str | None
    root_grant_id: str


def verify_scope_monotonicity(
    chain: list[DelegatedToken],
    root_grant_scopes: FrozenSet[str],
) -> None:
    """Enforce the delegation invariant across an AAIF token-exchange chain.

    Two checks, both required:
      1. Per-hop: each child's scopes are a subset of its parent's scopes.
      2. Origin: the leaf's scopes are a subset of the root grant's scopes.

    Check 2 is the one that catches inheritance-of-inflation: a parent that
    was itself over-scoped will pass check 1 for its child while the child
    still exceeds the root grant. Comparing against the origin, not the
    proximate parent, is what bounds the failure.
    """
    if not chain:
        raise ScopeInheritanceViolation("empty delegation chain")

    # Check 1: per-hop subset relation.
    for i in range(1, len(chain)):
        parent, child = chain[i - 1], chain[i]
        if not child.scopes.issubset(parent.scopes):
            raise ScopeInheritanceViolation(
                f"hop {i}: subject {child.subject!r} scopes "
                f"{sorted(child.scopes)} not a subset of parent "
                f"{parent.subject!r} scopes {sorted(parent.scopes)}"
            )

    # Check 2: leaf against origin grant.
    leaf = chain[-1]
    if not leaf.scopes.issubset(root_grant_scopes):
        inflated = leaf.scopes - root_grant_scopes
        raise ScopeInheritanceViolation(
            f"leaf subject {leaf.subject!r} (root_grant={leaf.root_grant_id}) "
            f"carries scopes {sorted(inflated)} not present in root grant "
            f"{sorted(root_grant_scopes)}; inheritance-of-inflation detected"
        )


def detect_unchanged_scope_across_chain(chain: list[DelegatedToken]) -> bool:
    """Heuristic tell: a chain of length >= 2 where every hop carries the
    identical scope set is almost always un-narrowed inheritance. Flag for
    review even if subset checks pass (they will, trivially)."""
    if len(chain) < 2:
        return False
    first = chain[0].scopes
    return all(t.scopes == first for t in chain[1:])
