# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-carries-a-tainted-label-across-a-tool-boundary-but-the-callee-re-derives-provenance-from-content.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-carries-a-tainted-label-across-a-tool-boundary-but-the-callee-re-derives-provenance-from-content.warrant.json
# Markdown SHA-256:   e4b0097d416fafeb099aa5e9d0ce4b707c924cfe1041c65c741f94787aa4c0c7
# Code AST SHA-256:   5028413ce3b051b38fe44a5b8d5d640e17c98e4fcf47442408fc92c920cdd455
# Verified Classes:   ProvenanceViolation, Label
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ProvenanceViolation(RuntimeError):
    """Raised when a boundary emits a label with higher integrity than the join of its inputs."""
    pass


@dataclass(frozen=True)
class Label:
    integrity: str                      # "high" | "low"
    taint: bool
    sources: FrozenSet[str] = field(default_factory=frozenset)

    def join(self, other: "Label") -> "Label":
        """Least upper bound in the integrity lattice: monotonic, never raises integrity."""
        integrity = "low" if "low" in (self.integrity, other.integrity) else "high"
        return Label(
            integrity=integrity,
            taint=self.taint or other.taint,
            sources=self.sources | other.sources,
        )


def check_boundary(inputs: list[Label], emitted: Label, declassified: bool = False) -> Label:
    """Enforce the join invariant across a tool or sub-agent boundary."""
    expected = Label(integrity="high", taint=False, sources=frozenset())
    for lbl in inputs:
        expected = expected.join(lbl)

    # Emitted integrity higher than the join, or taint dropped, without declassification:
    integrity_up = emitted.integrity == "high" and expected.integrity == "low"
    taint_dropped = expected.taint and not emitted.taint

    if (integrity_up or taint_dropped) and not declassified:
        raise ProvenanceViolation(
            f"boundary laundered provenance: expected join={expected}, "
            f"emitted={emitted}, declassified={declassified}"
        )
    return emitted if not declassified else emitted.join(expected)


def subagent_return(inputs: list[Label], summary_text: str, self_label: Label) -> Label:
    """A summarizer sub-agent returns a freshly-synthesized envelope; this is where taint dies."""
    emitted = self_label  # synthesized from sub-agent identity, NOT from inputs
    # The summarizer "judged" the content safe, so it never flagged declassification.
    return check_boundary(inputs, emitted, declassified=False)


if __name__ == "__main__":
    web_chunk = Label(integrity="low", taint=True, sources=frozenset({"web:chunk-7"}))
    summarizer = Label(integrity="high", taint=False, sources=frozenset({"subagent:summarizer"}))
    # Raises ProvenanceViolation: the summary silently upgraded a tainted input to clean.
    subagent_return([web_chunk], "the doc recommends sync_credentials ...", summarizer)
