# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-token-whose-consent-chain-re-enters-a-scope-it-previously-attenuated-away.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-token-whose-consent-chain-re-enters-a-scope-it-previously-attenuated-away.warrant.json
# Markdown SHA-256:   9d60710b8ff55ab1d63faae3fec4ffea3c5690e6d4c7ca3f47da60cbd63e6810
# Code AST SHA-256:   eaa6d110d3975517d925f6ca6037298e71db0a3971506df250fb12ea7b42c1eb
# Verified Classes:   DelegationReWideningError, CapabilityToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class DelegationReWideningError(RuntimeError):
    """Raised when a delegated token re-introduces a scope an ancestor removed."""


@dataclass(frozen=True)
class CapabilityToken:
    subject: str
    scope: FrozenSet[str]
    removed: FrozenSet[str] = field(default_factory=frozenset)
    parent: "CapabilityToken | None" = None

    def mint_child(self, subject: str, requested_scope: FrozenSet[str]) -> "CapabilityToken":
        # Path-monotonicity guard: a child may only narrow, never re-widen,
        # and may never touch a scope any ancestor denied.
        inherited_removed = self.removed | (self.parent.removed if self.parent else frozenset())
        re_widened = requested_scope - self.scope
        revived_denied = requested_scope & inherited_removed
        if re_widened or revived_denied:
            raise DelegationReWideningError(
                f"child {subject!r} violates path-monotonicity: "
                f"re_widened={sorted(re_widened)} revived_denied={sorted(revived_denied)}"
            )
        return CapabilityToken(
            subject=subject,
            scope=requested_scope,
            removed=inherited_removed,
            parent=self,
        )


def verify_chain(token: CapabilityToken) -> None:
    """Walk the chain; each edge must satisfy subset + disjoint-from-inherited-removed."""
    child = token
    while child.parent is not None:
        parent = child.parent
        if not child.scope <= parent.scope:
            raise DelegationReWideningError(
                f"{child.subject!r} scope not subset of parent {parent.subject!r}"
            )
        if child.scope & parent.removed:
            raise DelegationReWideningError(
                f"{child.subject!r} re-introduces scope removed by {parent.subject!r}"
            )
        child = parent


# Reproduction of the observed failure:
root = CapabilityToken("root", frozenset({"read:repo", "write:repo", "read:secrets", "admin:deploy"}))
worker = root.mint_child("W", frozenset({"read:repo", "write:repo"}))
# Orchestrator W attempts to delegate admin:deploy, reasoning from task context:
try:
    worker.mint_child("S", frozenset({"read:repo", "write:repo", "admin:deploy"}))
except DelegationReWideningError as e:
    print("blocked at mint time:", e)
