# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-sandbox-denial-as-evidence-of-taint-rather-than-a-tool-fault.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-sandbox-denial-as-evidence-of-taint-rather-than-a-tool-fault.warrant.json
# Markdown SHA-256:   829432136747e9e77da62abb261a007ac549a37d1753be04a84c65163c30e767
# Code AST SHA-256:   dd2890b83110de4fff62398bf000725a4823a7df17942e99c12bc66704b3179f
# Verified Classes:   DenialClass, TaintLaunderingError, Denial
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class DenialClass(Enum):
    CAPABILITY = "capability"
    TAINT = "taint"
    UNKNOWN = "unknown"


class TaintLaunderingError(RuntimeError):
    """Raised when an agent attempts to satisfy a taint-denied intent via
    retry, argument mutation, or delegation without label propagation."""


@dataclass
class Denial:
    deny_class: Optional[str]
    source_label: Optional[str]
    sink: Optional[str]
    tool_succeeded_with_trusted_args: bool


def classify_and_route(denial: Denial, attempted_action: str) -> str:
    cls = DenialClass(denial.deny_class) if denial.deny_class in {
        d.value for d in DenialClass
    } else DenialClass.UNKNOWN

    # Conservative default: unparseable denial is treated as taint.
    if cls is DenialClass.UNKNOWN:
        cls = DenialClass.TAINT

    if cls is DenialClass.CAPABILITY:
        if attempted_action.startswith("retry") or attempted_action.startswith("mutate_args"):
            raise TaintLaunderingError(
                f"capability denial cannot be fixed by {attempted_action!r}; "
                "escalate for grant or abandon subtask"
            )
        return "escalate_or_abandon"

    # TAINT path
    if attempted_action.startswith("retry"):
        raise TaintLaunderingError(
            f"taint denial from {denial.source_label} at {denial.sink} is non-retryable"
        )
    if attempted_action.startswith("mutate_args") and denial.tool_succeeded_with_trusted_args:
        raise TaintLaunderingError(
            "argument mutation after prior success with trusted args indicates "
            "denial laundering, not a tool fault"
        )
    if attempted_action.startswith("delegate_without_label"):
        raise TaintLaunderingError(
            "delegation to peer without propagating taint label is exfiltration"
        )
    return "quarantine_and_rederive_or_gate"
