# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-context-segment-before-a-tool-call-and-why-label-propagation-alone-cannot-answer-this.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-context-segment-before-a-tool-call-and-why-label-propagation-alone-cannot-answer-this.warrant.json
# Markdown SHA-256:   4a8fbc585b89ff13a184009d25eb7d10404116b9b4ca1ad7c213b98e6b9f53e3
# Code AST SHA-256:   a3e51dec17c16cf58a1e27e460862c31260c6947bda42d370d291150548abcd8
# Verified Classes:   TaintReachabilityError, Label, Node, Witness, EpisodeGraph
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class TaintReachabilityError(RuntimeError):
    """Raised when a side-effecting tool call's arguments are dataflow-reachable
    from an untrusted node and no declassification witness sits on the path."""


class Label(Enum):
    TRUSTED = "T"
    UNTRUSTED = "U"

    def join(self, other: "Label") -> "Label":
        # Lattice join: U dominates T.
        return Label.UNTRUSTED if Label.UNTRUSTED in (self, other) else Label.TRUSTED


@dataclass(frozen=True)
class Node:
    node_id: str
    label: Label
    parents: tuple[str, ...] = ()


@dataclass(frozen=True)
class Witness:
    declassifier: str
    constraint: str


@dataclass
class EpisodeGraph:
    """Per-episode dataflow graph. Quarantine state must be externalized
    (persisted outside the context window) so it survives compaction."""

    nodes: dict[str, Node] = field(default_factory=dict)
    witnesses: dict[str, Witness] = field(default_factory=dict)  # node_id -> witness

    def add(self, node: Node) -> None:
        self.nodes[node.node_id] = node

    def declassify(self, node_id: str, witness: Witness) -> None:
        # A declassification is only valid on the node it names.
        if node_id not in self.nodes:
            raise TaintReachabilityError(f"declassify on unknown node {node_id}")
        self.witnesses[node_id] = witness

    def _ancestors(self, node_id: str) -> Iterable[str]:
        stack = [node_id]
        seen: set[str] = set()
        while stack:
            current = stack.pop()
            if current in seen:
                continue
            seen.add(current)
            yield current
            stack.extend(self.nodes[current].parents)

    def is_reachable_from_untrusted(self, node_id: str) -> bool:
        return any(
            self.nodes[a].label is Label.UNTRUSTED for a in self._ancestors(node_id)
        )

    def has_witness_on_path(self, node_id: str) -> bool:
        return any(a in self.witnesses for a in self._ancestors(node_id))


def guard_side_effecting_call(
    graph: EpisodeGraph, arg_node_id: str, tool_name: str
) -> None:
    """The pre-call invariant: block iff reachable-from-untrusted with no witness.

    Label membership alone is insufficient (the summarizer launders it) and
    unnecessary (inert taint in context must not be quarantined).
    """
    if arg_node_id not in graph.nodes:
        raise TaintReachabilityError(
            f"argument node {arg_node_id} not in episode graph for {tool_name}"
        )
    reachable = graph.is_reachable_from_untrusted(arg_node_id)
    witnessed = graph.has_witness_on_path(arg_node_id)

    if reachable and not witnessed:
        raise TaintReachabilityError(
            f"blocked {tool_name}: arg {arg_node_id} reachable from untrusted "
            f"source with no declassification witness on path"
        )
    # reachable + witnessed -> proceed and log witness
    # not reachable       -> proceed (inert taint retained, not quarantined)
