# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-consent-token-whose-scope-was-silently-widened-by-the-aaif-re-delegation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-consent-token-whose-scope-was-silently-widened-by-the-aaif-re-delegation-chain.warrant.json
# Markdown SHA-256:   fcc8a76c187ee91daf5e85d9d32775e1fc1d9a8a1d6b494efb7870be4ac36fb1
# Code AST SHA-256:   b4d9a5f521d9d710e47949046f521ae4b646a67b5d31a0e4ecdd68b8401bd269
# Verified Classes:   ScopeWideningError, ActClaim, ConsentToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeWideningError(RuntimeError):
    """Raised when a delegated consent token's scope exceeds an intermediate hop's grant."""


@dataclass(frozen=True)
class ActClaim:
    sub: str
    scope: FrozenSet[str]


@dataclass(frozen=True)
class ConsentToken:
    leaf_scope: FrozenSet[str]
    chain: tuple  # ordered P -> A1 -> ... -> An


def verify_chain_monotonicity(token: ConsentToken) -> None:
    """Enforce scope(T) <= scope(An) <= ... <= scope(P) across the act chain.

    Leaf signature validity is assumed already checked by the transport layer.
    This function enforces the invariant the transport does NOT check.
    """
    if not token.chain:
        raise ScopeWideningError("empty act chain: cannot establish monotonicity")

    # Leaf must be contained in its immediate delegator's scope.
    immediate = token.chain[-1]
    if not token.leaf_scope.issubset(immediate.scope):
        raise ScopeWideningError(
            f"leaf scope {sorted(token.leaf_scope)} not subset of "
            f"delegator {immediate.sub} scope {sorted(immediate.scope)}"
        )

    # Each hop must narrow or preserve relative to its parent.
    for parent, child in zip(token.chain, token.chain[1:]):
        if not child.scope.issubset(parent.scope):
            raise ScopeWideningError(
                f"hop {child.sub} widened scope: {sorted(child.scope)} "
                f"not subset of parent {parent.sub} scope {sorted(parent.scope)}"
            )


def construct_delegation(inbound: FrozenSet[str], requested: FrozenSet[str]) -> FrozenSet[str]:
    """Deterministic narrowing. Never call an LLM here."""
    effective = inbound & requested
    if not effective:
        raise ScopeWideningError(
            f"requested {sorted(requested)} disjoint from inbound {sorted(inbound)}"
        )
    return effective


# Reproduce the observed failure: W copies union of context + tool schema.
P = ActClaim("principal", frozenset({"read:repo", "write:pr"}))
W = ActClaim("worker", frozenset({"write:pr"}))  # O narrowed deliberately
H = ActClaim("helper", frozenset({"write:pr", "read:repo"}))  # widened by W
token = ConsentToken(leaf_scope=H.scope, chain=(P, W, H))

verify_chain_monotonicity(token)  # raises ScopeWideningError
