# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-quarantine-tainted-context-from-trusted-instructions-when-retrieved-content-is-structurally-indistinguishable-from.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-quarantine-tainted-context-from-trusted-instructions-when-retrieved-content-is-structurally-indistinguishable-from.warrant.json
# Markdown SHA-256:   1e67022fbae40e49ae3d8c7588fa402bf968b4765ca6482f0833152c6750b619
# Code AST SHA-256:   52e6322bb1ca700fc88feedbe9a57fb0eeae642dcdbd7cc87d67de5f1d5e441b
# Verified Classes:   TaintCollapseError, Taint, Quarantine, TypedExtraction, ToolCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

"""Operational guard for taint collapse at the action-selection boundary.

Enforces per-sink taint gating over tool-call arguments. UNKNOWN arguments
are treated as TAINTED for sink-crossing tools. A turn-level flag is
deliberately NOT consulted; it is the failure mode this guard exists to
prevent.
"""

from __future__ import annotations

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


class TaintCollapseError(RuntimeError):
    """Raised when a sink-crossing tool call cannot be proven clean."""


class Taint(Enum):
    TRUSTED = 0
    UNKNOWN = 1
    TAINTED = 2


# Sink-crossing tools: their effects leave the trust boundary.
SINK_CROSSING = frozenset({"send", "write", "execute", "fetch"})
READ_ONLY = frozenset({"read", "search", "summarize", "extract"})


@dataclass(frozen=True)
class Quarantine:
    """Regions of context that hold untrusted retrieved content."""

    regions: tuple[str, ...]

    def contains(self, value: str) -> bool:
        # Normalize before comparison; adversarial content is often
        # whitespace- or case-mangled to defeat naive substring checks.
        needle = " ".join(value.lower().split())
        return any(needle in " ".join(r.lower().split()) for r in self.regions)


@dataclass(frozen=True)
class TypedExtraction:
    """A value produced by a schema-validated parser over a quarantined
    region. This is the ONLY legitimate declassification path."""

    value: str
    schema: str
    within_range: bool


@dataclass
class ToolCall:
    tool: str
    args: dict[str, object]
    provenance: dict[str, Taint] = field(default_factory=dict)


def classify(value: object, quarantine: Quarantine,
             extractions: Iterable[TypedExtraction]) -> Taint:
    if isinstance(value, TypedExtraction):
        return Taint.TRUSTED if value.within_range else Taint.TAINTED
    if not isinstance(value, str):
        return Taint.UNKNOWN
    if quarantine.contains(value):
        return Taint.TAINTED
    for ex in extractions:
        if ex.value == value and ex.within_range:
            return Taint.TRUSTED
    # Novel, untraceable value. Must be treated as TAINTED for sinks.
    return Taint.UNKNOWN


def gate(call: ToolCall, quarantine: Quarantine,
         extractions: Iterable[TypedExtraction]) -> ToolCall:
    if call.tool in READ_ONLY:
        return call
    if call.tool not in SINK_CROSSING:
        raise TaintCollapseError(
            f"tool {call.tool!r} has no sink classification; refusing to "
            f"guess whether its effects cross the trust boundary"
        )

    extractions = tuple(extractions)
    joined = Taint.TRUSTED
    resolved: dict[str, Taint] = {}
    for name, value in call.args.items():
        t = classify(value, quarantine, extractions)
        resolved[name] = t
        joined = t if t.value > joined.value else joined

    if joined is not Taint.TRUSTED:
        raise TaintCollapseError(
            f"sink-crossing call {call.tool!r} blocked: argument taint "
            f"join = {joined.name}; per-arg = "
            f"{ {k: v.name for k, v in resolved.items()} }. "
            f"A turn-level taint flag is not a substitute for value "
            f"provenance; reduce tainted content to typed extractions "
            f"in a separate turn before retrying."
        )

    call.provenance = resolved
    return call


def run_action(call: ToolCall, quarantine: Quarantine,
               extractions: Iterable[TypedExtraction]) -> ToolCall:
    """Entry point. Raises TaintCollapseError rather than firing a
    sink-crossing call whose arguments cannot be proven clean."""
    return gate(call, quarantine, extractions)
