# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-taint-label-monotonicity-across-a-sandboxed-tool-boundary-when-an-untrusted-document-is-partially-re-summarized-by-a-tr.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-taint-label-monotonicity-across-a-sandboxed-tool-boundary-when-an-untrusted-document-is-partially-re-summarized-by-a-tr.warrant.json
# Markdown SHA-256:   69d45a5abc34731f1c43fbca0d86ced2bcabc3fe64ff2082a0b92b67f5d43a35
# Code AST SHA-256:   4a6cadd3a95b5aa16c31fdd92e2c84e03de10b7674d3cc0e74493dac90489de7
# Verified Classes:   TaintMonotonicityViolation, Label, SubAgentManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintMonotonicityViolation(RuntimeError):
    """Raised when a sub-agent return lowers a taint label below join(inputs)."""


@dataclass(frozen=True)
class Label:
    untrusted: FrozenSet[str] = frozenset()

    def join(self, other: "Label") -> "Label":
        return Label(self.untrusted | other.untrusted)

    def __le__(self, other: "Label") -> bool:
        # self is at most as tainted as other
        return self.untrusted <= other.untrusted


@dataclass
class SubAgentManifest:
    name: str
    declassifier: bool = False
    output_domain_bounded: bool = False


def invoke_sub_agent(manifest: SubAgentManifest, inputs: list[Label],
                     declared_output: Label) -> Label:
    joined = Label()
    for lbl in inputs:
        joined = joined.join(lbl)

    if manifest.declassifier and manifest.output_domain_bounded:
        # Legitimate declassification: output alphabet cannot carry an instruction.
        return declared_output

    # Transformer: output must dominate the join of all inputs.
    if not (joined <= declared_output):
        raise TaintMonotonicityViolation(
            f"sub-agent '{manifest.name}' returned label {declared_output.untrusted} "
            f"that does not dominate input join {joined.untrusted}; "
            f"taint laundering detected at transformer boundary"
        )
    return declared_output


def sink_write_file(path: str, body: Label, policy_requires_clean: bool = True) -> None:
    if policy_requires_clean and body.untrusted:
        raise TaintMonotonicityViolation(
            f"sink rejected write to {path}: body tainted by {sorted(body.untrusted)}"
        )
    # ... perform write ...
