# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-propagate-taint-across-a-tool-call-boundary-that-the-sandbox-never-observes.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-propagate-taint-across-a-tool-call-boundary-that-the-sandbox-never-observes.warrant.json
# Markdown SHA-256:   951827da34207dcbb805c57799c8516374477d81c27ce7b76b0427a8b77bd780
# Code AST SHA-256:   106b32fd33d67a45b616346fef3822564e036a29c98a9c039ed7b41fa2b061ff
# Verified Classes:   TaintLeakError, Policy, Envelope, PlannerState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class TaintLeakError(RuntimeError):
    """Raised when a tool invocation could execute with control-flow-carried
    taint that the sandbox cannot observe in the argument payload."""


class Policy(Enum):
    FULL_ALLOW = "full_allow"
    READ_ONLY_ALLOW = "read_only_allow"
    DENY = "deny"


@dataclass(frozen=True)
class Envelope:
    tool: str
    argv: tuple[str, ...]
    taint: frozenset[str] = field(default_factory=frozenset)


@dataclass
class PlannerState:
    taint_set: set[str] = field(default_factory=set)

    def absorb_untrusted(self, label: str) -> None:
        # Monotone union: untrusted reads only ever add taint.
        self.taint_set.add(label)

    def declassify(self, label: str, justification: str) -> None:
        if not justification.strip():
            raise TaintLeakError(
                f"declassification of {label!r} requires a non-empty justification"
            )
        self.taint_set.discard(label)


def serialize(state: PlannerState, tool: str, argv: tuple[str, ...]) -> Envelope:
    # The invariant: the envelope carries the planner's current taint set,
    # NOT a content scan of argv. Control-flow-carried taint is preserved.
    return Envelope(tool=tool, argv=argv, taint=frozenset(state.taint_set))


def syscall_policy(env: Envelope) -> Policy:
    # Authoritative on envelope taint, independent of argument bytes.
    if env.taint:
        return Policy.READ_ONLY_ALLOW
    return Policy.FULL_ALLOW


def dispatch(state: PlannerState, tool: str, argv: tuple[str, ...]) -> Policy:
    env = serialize(state, tool, argv)
    policy = syscall_policy(env)

    # Guardrail: an exec-capable tool must never reach FULL_ALLOW while the
    # planner carries taint, regardless of what the arguments look like.
    if tool == "run_cmd" and policy is Policy.FULL_ALLOW and state.taint_set:
        raise TaintLeakError(
            "run_cmd resolved to FULL_ALLOW with non-empty planner taint: "
            f"taint={sorted(state.taint_set)} argv={argv}"
        )
    return policy


# --- failing trace: control-flow taint, benign-looking argv ---
state = PlannerState()
state.absorb_untrusted("UNTRUSTED_DOC")  # fetched poisoned document
try:
    # Planner chose run_cmd *because of* the document; argv has no doc bytes.
    dispatch(state, "run_cmd", ("cat", "/etc/agent/credentials"))
except TaintLeakError as exc:
    print(f"blocked: {exc}")

# --- correct path: declassify with justification, then exec is permitted ---
state.declassify("UNTRUSTED_DOC", "auditor confirmed no exfil intent in task 4471")
assert dispatch(state, "run_cmd", ("cat", "/etc/agent/credentials")) is Policy.FULL_ALLOW
