# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-taint-label-it-cannot-discharge-silent-capability-collapse-at-the-taint-aware-gate.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-taint-label-it-cannot-discharge-silent-capability-collapse-at-the-taint-aware-gate.warrant.json
# Markdown SHA-256:   ccc985e9a6ff612e6a134f27ba05e8f48d74952158771992344591a879ad8d24
# Code AST SHA-256:   d195ff289a837076dc863690af921838ddd85a2dabbde78765473cef633c426c
# Verified Classes:   Taint, EffectClass, EffectClassCollapse, Tool, PolicyEngine
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class Taint(Enum):
    INTERNAL = "internal"
    EXTERNAL_UNTRUSTED = "external_untrusted"
    SECRET = "secret"


class EffectClass(Enum):
    EGRESS_TEXT = "egress_text"
    MUTATE_STATE = "mutate_state"
    READ_ONLY = "read_only"


class EffectClassCollapse(RuntimeError):
    """Raised when a taint gate would permit a tool whose effect-class peers are denied."""


@dataclass(frozen=True)
class Tool:
    name: str
    effect_class: EffectClass
    # taints under which this tool is permitted, per its individually-authored gate
    permitted_taints: FrozenSet[Taint]


@dataclass
class PolicyEngine:
    registry: dict[str, Tool] = field(default_factory=dict)

    def register(self, tool: Tool) -> None:
        # Invariant: a tool may only join an effect class if adding it does not
        # widen the class's effective permission under any taint. The class gate
        # is the meet (intersection) of all member gates.
        peers = [t for t in self.registry.values() if t.effect_class is tool.effect_class]
        for peer in peers:
            class_gate = peer.permitted_taints & tool.permitted_taints
            widened = (peer.permitted_taints | tool.permitted_taints) - class_gate
            if widened:
                raise EffectClassCollapse(
                    f"registering {tool.name!r} into {tool.effect_class.value} would widen "
                    f"permission under taints {sorted(t.value for t in widened)}; "
                    f"peer {peer.name!r} gate={sorted(t.value for t in peer.permitted_taints)}, "
                    f"new gate={sorted(t.value for t in tool.permitted_taints)}. "
                    f"Reclassify or re-gate before registration."
                )
        self.registry[tool.name] = tool

    def authorize(self, tool_name: str, taint: FrozenSet[Taint]) -> None:
        tool = self.registry[tool_name]
        # Evaluate at effect-class granularity: the class gate is the meet of all
        # member gates, so a denial on any peer closes the class for this taint.
        class_gate = frozenset.intersection(
            *(p.permitted_taints for p in self.registry.values()
              if p.effect_class is tool.effect_class)
        )
        if not taint <= class_gate:
            raise EffectClassCollapse(
                f"denied {tool_name!r}: taint {sorted(t.value for t in taint)} "
                f"exceeds effect-class gate for {tool.effect_class.value} "
                f"({sorted(t.value for t in class_gate)}). "
                f"Class is closed; escalation or auditor declassification required."
            )


# Trace: the observed run.
engine = PolicyEngine()
engine.register(Tool("write_internal_wiki", EffectClass.EGRESS_TEXT,
                     frozenset({Taint.INTERNAL})))
engine.register(Tool("send_email", EffectClass.EGRESS_TEXT,
                     frozenset({Taint.INTERNAL, Taint.EXTERNAL_UNTRUSTED})))
# The next registration is the one that silently widened the class in the observed
# run; here it raises instead of permitting taint-laundering by substitution.
engine.register(Tool("create_calendar_event", EffectClass.EGRESS_TEXT,
                     frozenset({Taint.INTERNAL, Taint.EXTERNAL_UNTRUSTED, Taint.SECRET})))

tainted = frozenset({Taint.EXTERNAL_UNTRUSTED})
engine.authorize("create_calendar_event", tainted)  # unreachable; registration already raised
