# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scope-re-widening-in-aaif-delegated-credential-chains-across-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scope-re-widening-in-aaif-delegated-credential-chains-across-agent-handoffs.warrant.json
# Markdown SHA-256:   33d42f0812acf40da1557e3b6d425ed7393fd1ac5472e548e1b4a84262b85328
# Code AST SHA-256:   142c6bd6832ea26715567b83a07864d7186c20f30fe97067eb8c397222cc03ee
# Verified Classes:   ScopeAmplificationError, Hop
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

class ScopeAmplificationError(RuntimeError):
    """Raised when a delegated envelope widens scope relative to any ancestor."""
    pass

@dataclass(frozen=True)
class Hop:
    agent_id: str
    granted: FrozenSet[str]
    dropped: FrozenSet[str] = field(default_factory=frozenset)

def verify_chain(chain: list[Hop]) -> FrozenSet[str]:
    if not chain:
        raise ScopeAmplificationError("empty chain: no root authority")
    effective = chain[0].granted
    revoked: set[str] = set()
    for i, hop in enumerate(chain[1:], start=1):
        # Invariant 1: nearest-ancestor attenuation (no re-introduction of dropped caps)
        reintroduced = hop.granted & revoked
        if reintroduced:
            raise ScopeAmplificationError(
                f"hop {i} ({hop.agent_id}) re-introduced revoked scopes: {sorted(reintroduced)}"
            )
        # Invariant 2: strict subset against immediate parent, not root provenance
        widened = hop.granted - chain[i - 1].granted
        if widened:
            raise ScopeAmplificationError(
                f"hop {i} ({hop.agent_id}) widened beyond parent: {sorted(widened)}"
            )
        revoked |= hop.dropped
        effective = effective & hop.granted
        # Invariant 3: declared grant must equal root-anchored intersection
        if hop.granted != effective:
            raise ScopeAmplificationError(
                f"hop {i} ({hop.agent_id}) declared {sorted(hop.granted)} "
                f"but effective intersection is {sorted(effective)}"
            )
    return effective

def delegate(parent: Hop, child_id: str, requested: FrozenSet[str]) -> Hop:
    if not requested <= parent.granted:
        raise ScopeAmplificationError(
            f"{child_id} requested {sorted(requested - parent.granted)} not held by {parent.agent_id}"
        )
    dropped = parent.granted - requested
    return Hop(agent_id=child_id, granted=requested, dropped=dropped)

# Reproduction of the observed failure: P drops egress, E tries to reclaim it.
root = Hop("R", frozenset({"files:read", "files:write", "net:egress:internal"}))
planner = delegate(root, "P", frozenset({"files:read", "files:write"}))
# Executor reconstructed scope from root manifest instead of planner envelope:
executor = Hop("E", frozenset({"files:read", "net:egress:internal"}))
verify_chain([root, planner, executor])  # raises ScopeAmplificationError
