# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tool-call-argument-whose-taint-lattice-collapses-during-re-planning-rather-than-trust-its-provenan.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tool-call-argument-whose-taint-lattice-collapses-during-re-planning-rather-than-trust-its-provenan.warrant.json
# Markdown SHA-256:   7be6f465002d56cbfd27999418e02aabdedd8dc629299a854180008554d93ef5
# Code AST SHA-256:   ed8541261d3d7036e53f72edd275998b31193c033bb7ff677b7658d198be402f
# Verified Classes:   TaintClosureError, Segment, ProvenanceGate
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintClosureError(RuntimeError):
    """Raised when a tool-call argument's provenance ancestry is incomplete,
    cyclic, or exceeds the policy ceiling, so the call must be quarantined."""
    pass


# Taint lattice: UNTRUSTED < AGENT_DERIVED < TRUSTED, with join = max.
_ORDER = {"UNTRUSTED": 0, "AGENT_DERIVED": 1, "TRUSTED": 2}


def join(taints):
    if not taints:
        return None  # undefined: no ancestry recorded
    return max(taints, key=lambda t: _ORDER[t])


@dataclass
class Segment:
    id: str
    taint: str
    parents: tuple = field(default_factory=tuple)  # ids of segments consumed


class ProvenanceGate:
    def __init__(self, ceiling: str = "AGENT_DERIVED"):
        self.segments = {}
        self.ceiling = ceiling

    def register(self, seg: Segment):
        if seg.taint not in _ORDER:
            raise TaintClosureError(f"invalid taint {seg.taint!r} on {seg.id}")
        # Provenance-closure invariant: taint must dominate all parents.
        if seg.parents:
            parent_taints = [self.segments[p].taint for p in seg.parents if p in self.segments]
            if len(parent_taints) != len(seg.parents):
                raise TaintClosureError(
                    f"segment {seg.id} references unknown parent; ancestry incomplete")
            derived = join(parent_taints)
            if _ORDER[seg.taint] < _ORDER[derived]:
                raise TaintClosureError(
                    f"segment {seg.id} declares taint={seg.taint} but its parents "
                    f"join to {derived}; provenance laundering detected")
        self.segments[seg.id] = seg

    def _ancestry_taint(self, seg_id: str, seen: Optional[set] = None) -> str:
        seen = seen or set()
        if seg_id in seen:
            raise TaintClosureError(f"cycle in provenance ancestry at {seg_id}")
        seen.add(seg_id)
        seg = self.segments.get(seg_id)
        if seg is None:
            raise TaintClosureError(f"unknown segment {seg_id}; ancestry incomplete")
        if not seg.parents:
            return seg.taint
        return join([self._ancestry_taint(p, seen) for p in seg.parents])

    def admit_tool_call(self, tool: str, arg_from: str):
        try:
            taint = self._ancestry_taint(arg_from)
        except TaintClosureError as e:
            raise TaintClosureError(
                f"quarantine {tool}: cannot establish provenance for arg from "
                f"{arg_from}: {e}") from e
        if taint is None:
            raise TaintClosureError(
                f"quarantine {tool}: no ancestry recorded for {arg_from}; "
                f"free-form re-plan must fail closed")
        if _ORDER[taint] > _ORDER[self.ceiling]:
            raise TaintClosureError(
                f"quarantine {tool}: arg from {arg_from} inherits {taint} > "
                f"ceiling {self.ceiling}")
        return True
