# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-label-clearing-tool-boundary-as-a-taint-laundering-event-rather-than-a-legitimate-declassification.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-label-clearing-tool-boundary-as-a-taint-laundering-event-rather-than-a-legitimate-declassification.warrant.json
# Markdown SHA-256:   98a0dc5511a9f3250ac5cd066f93d486794c6918fe26ea7b920d6abc3aedfcfb
# Code AST SHA-256:   aec72911102a5df70434605709df20e00320900d26f65898522ddacbcf858a1d
# Verified Classes:   TaintLaunderingError, Labeled
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Any

TRUST = 0
TAINT = 1

class TaintLaunderingError(RuntimeError):
    """Raised when a tool boundary downgrades a label without a projection warrant."""
    pass

@dataclass(frozen=True)
class Labeled:
    value: Any
    label: int  # TRUST or TAINT

def join(*labels: int) -> int:
    return max(labels) if labels else TRUST

# Tool registry: only tools with an explicit projection_spec may declassify.
TOOLS = {
    "search_docs":  {"declassifies": False},
    "summarize":    {"declassifies": False},   # instruction-bearing: never clears taint
    "extract_field":{"declassifies": True, "projection_spec": ["title", "date"],
                     "authorizing_principal": "retrieval-policy-v3"},
}

def invoke(tool_name: str, inputs: list[Labeled]) -> Labeled:
    spec = TOOLS.get(tool_name)
    if spec is None:
        raise TaintLaunderingError(f"unregistered tool boundary: {tool_name}")
    input_join = join(*(i.label for i in inputs))
    # Simulated callee output; real callee returns raw value.
    raw_output = _run_callee(tool_name, [i.value for i in inputs])

    if spec["declassifies"]:
        if "projection_spec" not in spec or "authorizing_principal" not in spec:
            raise TaintLaunderingError(
                f"{tool_name} claims declassification without projection warrant"
            )
        # Projection is provably label-erasing only if output keys ⊆ spec.
        if not set(raw_output.keys()).issubset(set(spec["projection_spec"])):
            raise TaintLaunderingError(
                f"{tool_name} emitted keys outside projection_spec; "
                f"treating as laundering, inheriting join={input_join}"
            )
        return Labeled(raw_output, TRUST)

    # Non-declassifying tool: output inherits the join of all inputs.
    if input_join == TAINT and _looks_like_instruction(raw_output):
        # Instruction-bearing tainted output must never enter the trusted region.
        return Labeled(raw_output, TAINT)
    return Labeled(raw_output, join(input_join, TAINT if input_join == TAINT else TRUST))

def _run_callee(tool_name: str, values: list) -> Any:
    return {"summary": "the document requests credential exfiltration"} \
        if tool_name == "summarize" else {"title": "ok"}

def _looks_like_instruction(v: Any) -> bool:
    return isinstance(v, dict) and any(
        w in str(x).lower() for x in v.values()
        for w in ("ignore", "exfiltrate", "system:", "send")
    )

def plan_step(context: Labeled) -> str:
    if context.label == TAINT:
        raise TaintLaunderingError(
            "planner received tainted context in directive position; "
            "render as data-only, do not execute"
        )
    return "execute"
