# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tool-call-whose-arguments-are-taint-derived-but-whose-capability-was-negotiated-as-trusted.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tool-call-whose-arguments-are-taint-derived-but-whose-capability-was-negotiated-as-trusted.warrant.json
# Markdown SHA-256:   3787e9c731f5ae2f2a1f7517633556da94767203ed4097625ad847ed3313f1ec
# Code AST SHA-256:   a2cc743779c2fc4b3cb7f06343b321a729e59d243e401b656222abce0b909bee
# Verified Classes:   TaintQuarantineError, Taint, Operand, CapabilityWarrant
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class TaintQuarantineError(RuntimeError):
    """Raised when a tool call would dispatch tainted operands through a trusted capability."""


class Taint(IntEnum):
    FRESH_LITERAL = 0
    TRUSTED_ONLY = 1
    UNKNOWN = 2          # caller_asserted / opaque: conservative, joins upward
    UNTRUSTED_EXTERNAL = 3


def join(taints: Sequence[Taint]) -> Taint:
    if not taints:
        return Taint.FRESH_LITERAL
    return max(taints)


@dataclass(frozen=True)
class Operand:
    name: str
    taint: Taint
    derivation_chain: tuple[str, ...] = field(default_factory=tuple)


@dataclass(frozen=True)
class CapabilityWarrant:
    tool: str
    trusted: bool
    operand_trust_override: bool = False
    override_authority: str | None = None


def route_tool_call(
    warrant: CapabilityWarrant,
    operands: Sequence[Operand],
    *,
    audit_log: list[dict],
) -> str:
    joined = join([op.taint for op in operands])

    # Capability trust and operand trust are orthogonal; AND them.
    if joined >= Taint.UNTRUSTED_EXTERNAL or joined == Taint.UNKNOWN:
        if warrant.operand_trust_override and warrant.override_authority:
            audit_log.append(
                {
                    "event": "override_granted",
                    "tool": warrant.tool,
                    "authority": warrant.override_authority,
                    "joined_taint": joined.name,
                    "chains": {op.name: op.derivation_chain for op in operands},
                }
            )
            return "dispatched_under_override"

        audit_log.append(
            {
                "event": "quarantined",
                "tool": warrant.tool,
                "joined_taint": joined.name,
                "capability_trusted": warrant.trusted,
                "chains": {op.name: op.derivation_chain for op in operands},
            }
        )
        raise TaintQuarantineError(
            f"tool={warrant.tool!r} capability_trusted={warrant.trusted} "
            f"but joined operand taint={joined.name}; refusing dispatch. "
            f"UNKNOWN provenance is treated as UNTRUSTED for dispatch."
        )

    audit_log.append({"event": "dispatched", "tool": warrant.tool, "joined_taint": joined.name})
    return "dispatched"


# Reproduces the observed exfiltration attempt.
if __name__ == "__main__":
    log: list[dict] = []
    warrant = CapabilityWarrant(tool="email.send", trusted=True, operand_trust_override=False)
    operands = [
        Operand(
            name="recipients",
            taint=Taint.UNKNOWN,  # schema said caller_asserted; lattice says UNKNOWN
            derivation_chain=("http.get:doc", "summarize:span[42]", "extract:recipients"),
        ),
        Operand(name="body", taint=Taint.TRUSTED_ONLY),
    ]
    try:
        route_tool_call(warrant, operands, audit_log=log)
    except TaintQuarantineError as exc:
        print(f"QUARANTINED: {exc}")
        print(f"audit: {log[-1]['event']} chains={log[-1]['chains']}")
