# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-taint-provenance-on-retrieved-context-before-it-can-safely-act-on-a-vector-store-hit.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-taint-provenance-on-retrieved-context-before-it-can-safely-act-on-a-vector-store-hit.warrant.json
# Markdown SHA-256:   ecc5db116da127dfc3b12d1051245ba5f647afc58af905eb567f10f14792e0ae
# Code AST SHA-256:   154981cd934c04620ac47ee73c9fbf70c3b8306b7da21783ff88212252baa433
# Verified Classes:   TrustLevel, ContextItem, ToolCall, TaintViolationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class TrustLevel(Enum):
    TRUSTED = "trusted"
    UNTRUSTED = "untrusted"
    UNKNOWN = "unknown"


@dataclass(frozen=True)
class ContextItem:
    chunk_id: str
    source_uri: str
    text: str
    trust: TrustLevel


@dataclass(frozen=True)
class ToolCall:
    tool: str
    args: dict
    cited_chunk_ids: tuple[str, ...]


class TaintViolationError(RuntimeError):
    """Raised when a tool call is justified by context whose taint is not TRUSTED."""


TAINT_TOLERANT_TOOLS = frozenset({"search_docs", "summarize_context"})


def authorize_tool_call(
    call: ToolCall,
    active_context: Iterable[ContextItem],
) -> None:
    if call.tool in TAINT_TOLERANT_TOOLS:
        return

    by_id = {item.chunk_id: item for item in active_context}
    cited = [by_id[cid] for cid in call.cited_chunk_ids if cid in by_id]

    if not cited:
        # A non-tolerant tool invoked with no resolvable citation is itself a
        # provenance failure: we cannot prove the call was grounded in trusted context.
        raise TaintViolationError(
            f"tool={call.tool!r} has no resolvable cited context; "
            "cannot establish taint provenance"
        )

    offending = [item for item in cited if item.trust is not TrustLevel.TRUSTED]
    if offending:
        details = ", ".join(f"{i.chunk_id}({i.source_uri},{i.trust.value})" for i in offending)
        raise TaintViolationError(
            f"tool={call.tool!r} authorized by untrusted context: {details}"
        )
