# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-taint-label-collapse-at-the-inline-policy-enforcement-point-during-tool-call-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-taint-label-collapse-at-the-inline-policy-enforcement-point-during-tool-call-fan-out.warrant.json
# Markdown SHA-256:   34d825403759a5180659c14c69e0700538d2bf28b6b194da7bef272384671817
# Code AST SHA-256:   70e780d4a36fb55fc6dd42535bbd9baef7c52fb1ddbafe52c6646caa3d6a8e62
# Verified Classes:   TaintCollapseError, Provenance, ToolCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintCollapseError(RuntimeError):
    """Raised when the enforcement point cannot prove the argument label
    equals the join over argument provenance at decision time."""


@dataclass(frozen=True)
class Provenance:
    root_id: str
    label: str
    declassified_by: str | None = None


@dataclass
class ToolCall:
    name: str
    sink_class: str
    args_provenance: list[Provenance] = field(default_factory=list)
    asserted_label: str | None = None


SINK_RULES = {
    ("UNTRUSTED_EXTERNAL", "READ"): "allow",
    ("UNTRUSTED_EXTERNAL", "MUTATE_LOCAL"): "deny",
    ("UNTRUSTED_EXTERNAL", "EGRESS"): "deny",
    ("CLEAN", "READ"): "allow",
    ("CLEAN", "MUTATE_LOCAL"): "allow",
    ("CLEAN", "EGRESS"): "allow",
}

LABEL_ORDER = {"CLEAN": 0, "UNTRUSTED_EXTERNAL": 1}


def join_labels(provs: Iterable[Provenance]) -> str:
    label = "CLEAN"
    for p in provs:
        if p.declassified_by is None and LABEL_ORDER[p.label] > LABEL_ORDER[label]:
            label = p.label
    return label


def enforce(call: ToolCall) -> str:
    if not call.args_provenance:
        raise TaintCollapseError(
            f"call {call.name!r} has no argument provenance; "
            "cannot compute join, refusing to evaluate policy"
        )
    computed = join_labels(call.args_provenance)
    if call.asserted_label is not None and call.asserted_label != computed:
        raise TaintCollapseError(
            f"call {call.name!r}: asserted label {call.asserted_label!r} "
            f"!= provenance join {computed!r}; provenance likely severed "
            "by lossy planner step"
        )
    decision = SINK_RULES.get((computed, call.sink_class))
    if decision is None:
        raise TaintCollapseError(
            f"no rule for ({computed!r}, {call.sink_class!r}); "
            "failing closed"
        )
    return decision


def run_step(calls: list[ToolCall]) -> dict[str, str]:
    results: dict[str, str] = {}
    for c in calls:
        results[c.name] = enforce(c)
    return results


if __name__ == "__main__":
    step = [
        ToolCall("search_kb", "READ",
                 [Provenance("msg:42", "UNTRUSTED_EXTERNAL")]),
        ToolCall("write_note", "MUTATE_LOCAL",
                 [Provenance("msg:42", "UNTRUSTED_EXTERNAL")],
                 asserted_label="CLEAN"),
        ToolCall("post_webhook", "EGRESS",
                 [Provenance("msg:42", "UNTRUSTED_EXTERNAL")]),
    ]
    try:
        run_step(step)
    except TaintCollapseError as e:
        print(f"halted: {e}")
