# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-terminate-a-tainted-tool-call-graph-and-why-provenance-propagation-alone-cannot-answer-it.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-terminate-a-tainted-tool-call-graph-and-why-provenance-propagation-alone-cannot-answer-it.warrant.json
# Markdown SHA-256:   99f6d7ce4b57889290c46f3dc98ef176d4acad7935156924fe266597b936935d
# Code AST SHA-256:   acd3924efffa56278fe1147d18ac35e65d090e7daf9a44adabc1bdb7aa0231ad
# Verified Classes:   TrustClass, TaintPropagationOverflow, TaintedInvocationTerminated, TaintToken, EpisodeState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Optional


class TrustClass(IntEnum):
    WEB = 0
    USER_SUPPLIED = 1
    AGENT_GENERATED = 2
    SYSTEM = 3


class TaintPropagationOverflow(RuntimeError):
    """Raised when a taint token exceeds the tracking horizon; provenance is unknown."""


class TaintedInvocationTerminated(RuntimeError):
    """Raised when a lower-trust taint token reaches a higher-authority sink."""

    def __init__(self, sink: str, source_id: str, trust: TrustClass,
                 authority: TrustClass, hop_distance: int) -> None:
        self.sink = sink
        self.source_id = source_id
        self.trust = trust
        self.authority = authority
        self.hop_distance = hop_distance
        super().__init__(
            f"terminated {sink}: token from {source_id} "
            f"(trust={trust.name}, authority={authority.name}, hops={hop_distance})"
        )


@dataclass(frozen=True)
class TaintToken:
    source_id: str
    trust_class: TrustClass
    hop_distance: int

    def advance(self) -> "TaintToken":
        return TaintToken(self.source_id, self.trust_class, self.hop_distance + 1)


@dataclass
class EpisodeState:
    tokens: set[TaintToken] = field(default_factory=set)
    max_hops: int = 4

    def absorb_into_planner(self, incoming: set[TaintToken]) -> None:
        # The planner is a taint-transmitting node: any token entering its
        # context is advanced by one hop and unioned into its output taint.
        for tok in incoming:
            self.tokens.add(tok.advance())


def dispatch_tool(sink: str, authority: TrustClass,
                  state: EpisodeState) -> None:
    """Enforce the edge-scoped termination invariant before invoking a tool."""
    for tok in state.tokens:
        if tok.trust_class >= authority:
            continue
        if tok.hop_distance > state.max_hops:
            raise TaintPropagationOverflow(
                f"token {tok.source_id} exceeded max_hops="
                f"{state.max_hops} at sink {sink}; provenance unknown"
            )
        # Lower-trust token reaching a higher-authority sink: terminate the
        # episode, not merely the call. The caller must discard state.
        raise TaintedInvocationTerminated(
            sink=sink,
            source_id=tok.source_id,
            trust=tok.trust_class,
            authority=authority,
            hop_distance=tok.hop_distance,
        )


def run_episode() -> None:
    state = EpisodeState(max_hops=4)
    # Hop 1: untrusted web fetch enters the planner context.
    state.absorb_into_planner({TaintToken("web:doc-42", TrustClass.WEB, 0)})
    # Hop 2: extract_entities returns into planner context again.
    state.absorb_into_planner({TaintToken("web:doc-42", TrustClass.WEB, 1)})
    # Hop 3: planner synthesizes create_calendar_event args. The taint is
    # laundered through the planner but must still be present in state.
    dispatch_tool("create_calendar_event", TrustClass.SYSTEM, state)


if __name__ == "__main__":
    run_episode()
