# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-scope-laundering-from-erasing-provenance-across-a2a-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-scope-laundering-from-erasing-provenance-across-a2a-handoffs.warrant.json
# Markdown SHA-256:   041f954f61abec3548ea68d1a75a0a598b5d4b44342dc330a747fa339deaa609
# Code AST SHA-256:   6f82d6a6582ae43649e97f6ca5855b3c103369ca6ab04f2b6d877ef80c2cfd11
# Verified Classes:   ProvenanceLaunderingError, WarrantEdge
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a child action's effective capabilities exceed the granted set."""


@dataclass(frozen=True)
class WarrantEdge:
    parent_id: str
    child_id: str
    held: FrozenSet[str]
    granted: FrozenSet[str]

    @property
    def discarded(self) -> FrozenSet[str]:
        return self.held - self.granted

    def is_sound(self) -> bool:
        # Soundness requires that narrowing actually happened and is recorded.
        return self.granted.issubset(self.held)


def authorize_leaf_action(
    edge: WarrantEdge,
    effective_capabilities: FrozenSet[str],
    action: str,
) -> None:
    if not edge.is_sound():
        raise ProvenanceLaunderingError(
            f"edge {edge.parent_id}->{edge.child_id} grants capabilities "
            f"not held by parent: {edge.granted - edge.held}"
        )
    leaked = effective_capabilities - edge.granted
    if leaked:
        raise ProvenanceLaunderingError(
            f"action {action!r} by {edge.child_id} used capabilities outside "
            f"the recorded grant {edge.granted}: leaked={leaked}; "
            f"discarded={edge.discarded}; edge must be quarantined as "
            f"provenance_unsound"
        )
