# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-propagate-taint-labels-through-a-tool-chain-when-the-injection-arrives-mid-turn-and-the-label-set-changes-after-a-tool-call-has.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-propagate-taint-labels-through-a-tool-chain-when-the-injection-arrives-mid-turn-and-the-label-set-changes-after-a-tool-call-has.warrant.json
# Markdown SHA-256:   2273a4966959be2b9e4d4a510b7cbf992ad96f8655da0bba49b97b570ec6ba7f
# Code AST SHA-256:   7c37d2d2aa3307a668578dca56a0c6bbed63f49cfdb5f620eea008abdece2314
# Verified Classes:   TaintCommitViolation, Label
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Mapping


class TaintCommitViolation(RuntimeError):
    """Raised when a side-effecting call commits under a label set
    that does not dominate the join of its arguments' derivation labels."""


@dataclass(frozen=True)
class Label:
    trust: str                      # "trusted" | "untrusted-content"
    provenance: str                 # "user" | "file" | "self" | "tool"
    derived_from: FrozenSet[str] = field(default_factory=frozenset)

    def join(self, other: "Label") -> "Label":
        trust = "untrusted-content" if "untrusted-content" in (self.trust, other.trust) else "trusted"
        return Label(
            trust=trust,
            provenance=self.provenance if self.provenance == other.provenance else "mixed",
            derived_from=self.derived_from | other.derived_from,
        )


def join_all(labels) -> Label:
    out = Label(trust="trusted", provenance="user")
    for lb in labels:
        out = out.join(lb)
    return out


SINK_CLEARANCE: Mapping[str, str] = {
    "email:legal": "trusted",
    "email:partner@external.example": "trusted",
    "memory:episodic": "trusted",
}


def commit_tool_call(
    sink: str,
    arg_labels: list[Label],
    label_set_at_commit: Label,
    label_set_at_emit: Label,
) -> None:
    if sink not in SINK_CLEARANCE:
        raise TaintCommitViolation(f"unknown sink {sink!r}; cannot determine clearance")

    effective = label_set_at_commit.join(join_all(arg_labels))
    clearance = SINK_CLEARANCE[sink]

    if effective.trust == "untrusted-content" and clearance == "trusted":
        raise TaintCommitViolation(
            f"commit rejected: sink={sink} clearance={clearance} "
            f"effective_trust={effective.trust} "
            f"derived_from={sorted(effective.derived_from)} "
            f"(emit_label_trust={label_set_at_emit.trust}; "
            f"injection entered mid-batch)"
        )


def run_turn_two() -> None:
    # t2: contract read in t1 carried an injection; summary derived from it.
    contract = Label(trust="untrusted-content", provenance="file", derived_from=frozenset({"vendor.md"}))
    summary = Label(
        trust="untrusted-content",
        provenance="self",
        derived_from=frozenset({"vendor.md", "summary:turn2"}),
    )
    label_set_at_emit = Label(trust="trusted", provenance="user")          # pre-batch view
    label_set_at_commit = contract.join(label_set_at_emit)                 # post-batch view

    # The explicit exfiltration is caught by a destination check too.
    commit_tool_call("email:partner@external.example", [contract], label_set_at_commit, label_set_at_emit)

    # The derived summary to a *trusted* sink is the laundering path.
    commit_tool_call("email:legal", [summary], label_set_at_commit, label_set_at_emit)


if __name__ == "__main__":
    try:
        run_turn_two()
    except TaintCommitViolation as exc:
        # Expected: the summary call is rejected because its derivation join
        # carries untrusted-content even though the sink is trusted.
        print(f"guard fired: {exc}")
