# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-must-be-re-derived-at-every-tool-boundary-rather-than-inherited-from-the-retrieval-context.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-must-be-re-derived-at-every-tool-boundary-rather-than-inherited-from-the-retrieval-context.warrant.json
# Markdown SHA-256:   b860e5384fd53086fe56d001e39135bc84c9c22ce4ea744d7a18805e3d3d682f
# Code AST SHA-256:   aa83ed774b71b964ebdeb86e60fd9c88bcf97dc274e03309901b39036fe94b73
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a tool's trust contract permits model-emitted output to
    escape with a TRUSTED label while UNTRUSTED values are reachable."""
    pass


TRUST_INHERIT = "inherit"   # pure fn of args, no external read, no model gen
TRUST_LAUNDER = "launder"   # LLM-mediated or external read: output forced UNTRUSTED
TRUST_REDERIVE = "rederive" # reads external state: output UNTRUSTED by default


def resolve_output_label(tool_name: str, contract: str, arg_labels: set[str]) -> str:
    if contract == TRUST_INHERIT:
        # Safe only if the tool is statically known to be argument-pure.
        if is_llm_mediated(tool_name):
            raise TaintLaunderingError(
                f"tool {tool_name!r} declared {TRUST_INHERIT} but is LLM-mediated; "
                "model emissions are fresh allocations and cannot inherit labels"
            )
        return "UNTRUSTED" if "UNTRUSTED" in arg_labels else "TRUSTED"
    if contract in (TRUST_LAUNDER, TRUST_REDERIVE):
        return "UNTRUSTED"
    raise TaintLaunderingError(f"unknown trust contract {contract!r} for {tool_name!r}")


def guard_side_effect(tool_name: str, payload_is_handle: bool,
                      reachable_labels: set[str]) -> None:
    # The boundary is reachable taint, not the syntactic argument label.
    if not payload_is_handle and "UNTRUSTED" in reachable_labels:
        raise TaintLaunderingError(
            f"side-effecting tool {tool_name!r} received a free-form payload "
            "while UNTRUSTED values are reachable in context; "
            "require a labeled handle or explicit declassification"
        )
