# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-label-laundering-through-lossy-re-derivation-in-taint-tracked-agent-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-label-laundering-through-lossy-re-derivation-in-taint-tracked-agent-pipelines.warrant.json
# Markdown SHA-256:   48ebd5f48bad6addfcfd5daf4eff8f99ad5dc594b1de9d7b1da0c1e5c1d1d4d3
# Code AST SHA-256:   3f8e338299627629cc12450940c091a47eabd4ee8229f10c69c353bd68aa594e
# Verified Classes:   Taint, TaintJoinViolation, Labeled, Declassification, DerivationNode
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import FrozenSet


class Taint(IntEnum):
    CLEAN = 0
    TAINTED = 1


class TaintJoinViolation(RuntimeError):
    """Raised when a derivation node emits a value whose taint is lower than
    the join of its transitively-read labeled inputs, without an explicit,
    audited declassification event. This is the label-laundering guard."""


@dataclass(frozen=True)
class Labeled:
    value: object
    taint: Taint
    provenance: FrozenSet[str] = field(default_factory=frozenset)


@dataclass(frozen=True)
class Declassification:
    inputs: FrozenSet[str]
    justification: str          # payload-preservation argument, audited
    result_taint: Taint


class DerivationNode:
    """A stage that transforms labeled inputs into a new value.

    Invariant: output taint = join of ALL transitively-read input taints,
    unless an explicit Declassification is supplied. Lossy transforms
    (summarize/extract/embed/paraphrase) are taint-preserving by default.
    """

    def __init__(self, name: str):
        self.name = name
        self._declassifications: dict[str, Declassification] = {}

    def register_declassification(self, value_id: str, d: Declassification) -> None:
        # Declassification must be explicit, named, and audited out-of-band.
        self._declassifications[value_id] = d

    def derive(
        self,
        value_id: str,
        inputs: list[Labeled],
        transform: str,
        opaque_read: bool = False,
    ) -> Labeled:
        if opaque_read:
            # An untracked context assembly cannot be proven clean.
            raise TaintJoinViolation(
                f"node={self.name} value={value_id}: opaque read — cannot "
                f"enumerate transitively-read labels; refusing Clean default."
            )

        join = Taint(max((i.taint for i in inputs), default=Taint.CLEAN))
        prov = frozenset().union(*(i.provenance for i in inputs))

        if value_id in self._declassifications:
            d = self._declassifications[value_id]
            if d.result_taint > join:
                raise TaintJoinViolation(
                    f"node={self.name} value={value_id}: declassification "
                    f"raises taint {join.name}->{d.result_taint.name}; invalid."
                )
            # Explicit, audited downgrade — permitted.
            return Labeled(value=f"{transform}(...)", taint=d.result_taint, provenance=prov)

        # No declassification: lossy transform preserves the join.
        return Labeled(value=f"{transform}(...)", taint=join, provenance=prov)

    def emit_to_clean_store(self, out: Labeled) -> Labeled:
        if out.taint is not Taint.CLEAN:
            raise TaintJoinViolation(
                f"node={self.name}: refusing to write tainted value "
                f"({out.taint.name}, prov={sorted(out.provenance)}) to clean store; "
                f"semantic memory / caches / message buses require explicit declassification."
            )
        return out


def _demo() -> None:
    node = DerivationNode("extract")
    doc = Labeled(value="...injected doc...", taint=Taint.TAINTED, provenance=frozenset({"web:D"}))

    # Lossy extraction: taint preserved by join. Correct.
    facts = node.derive("F", [doc], transform="extract")
    assert facts.taint is Taint.TAINTED

    # Attempting to write laundered facts to the clean memory store fails loudly.
    node.emit_to_clean_store(facts)   # raises TaintJoinViolation

    # Opaque read (untracked context assembly) is a hard failure, not a Clean default.
    node.derive("G", [doc], transform="summarize", opaque_read=True)  # raises


if __name__ == "__main__":
    _demo()
