# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-capability-tokens-from-silently-widening-scope-across-multi-hop-agent-authorization-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-capability-tokens-from-silently-widening-scope-across-multi-hop-agent-authorization-chains.warrant.json
# Markdown SHA-256:   a7c64bf02ab92a21f007b019016689cf37c23591e2c0afd999be6f89f6a5e862
# Code AST SHA-256:   f19012e02e537f54fc67bcc72600ab11fe07f8e5d9d7eca4c8288ba537887410
# Verified Classes:   ScopeWideningError, CapabilityToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

class ScopeWideningError(RuntimeError):
    """Raised when a delegated token's scope exceeds its folded ancestry."""
    pass

@dataclass(frozen=True)
class CapabilityToken:
    token_id: str
    agent_id: str
    scope: FrozenSet[str]
    parent: "CapabilityToken | None" = None

    def folded_ancestor_scope(self) -> FrozenSet[str]:
        acc = self.scope
        node = self.parent
        while node is not None:
            acc = acc & node.scope
            node = node.parent
        return acc

def mint_child(parent: CapabilityToken, child_agent: str,
               requested: FrozenSet[str], child_id: str) -> CapabilityToken:
    # Compare against INHERITED effective scope, never the child's manifest.
    inherited = parent.folded_ancestor_scope()
    if not requested.issubset(inherited):
        raise ScopeWideningError(
            f"delegation to {child_agent} requests {sorted(requested - inherited)} "
            f"beyond folded inherited scope {sorted(inherited)}"
        )
    return CapabilityToken(child_id, child_agent, requested, parent=parent)

def verify_presentation(token: CapabilityToken) -> None:
    # Fold-check at presentation: catch manifest-drift and resume-inflation.
    folded = token.folded_ancestor_scope()
    if not token.scope.issubset(folded):
        raise ScopeWideningError(
            f"token {token.token_id} scope {sorted(token.scope)} "
            f"exceeds folded ancestry {sorted(folded)}"
        )

def resume_from_checkpoint(token_id: str, durable: dict[str, CapabilityToken],
                           reconstructed_scope: FrozenSet[str]) -> CapabilityToken:
    # A resumed agent may NOT re-mint from memory; it must reload the durable token.
    if token_id not in durable:
        raise ScopeWideningError(
            f"resume of {token_id} without durable token; reconstructed "
            f"scope {sorted(reconstructed_scope)} is untrusted"
        )
    token = durable[token_id]
    verify_presentation(token)
    return token
