# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-propagate-a-taint-label-when-a-tool-boundary-launders-provenance-through-a-re-serialization-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-propagate-a-taint-label-when-a-tool-boundary-launders-provenance-through-a-re-serialization-hop.warrant.json
# Markdown SHA-256:   8521555e5bb266c4c8a1d2e17c6098185de0fb06ff2d9154704d66f1454a2e2c
# Code AST SHA-256:   2331b7e7bbbadf845416190825ab991637ac285bd3d721bfac661c2cee3a0fef
# Verified Classes:   Taint, ProvenanceLaunderingError, Segment, ToolManifest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class Taint(Enum):
    TRUSTED = 0
    SYNTHESIZED = 1
    UNTRUSTED_EXTERNAL = 2


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a tool boundary would propagate a label that no longer
    soundly over-approximates the provenance of the output bytes."""


@dataclass
class Segment:
    text: str
    labels: frozenset = field(default_factory=lambda: frozenset({Taint.TRUSTED}))


@dataclass
class ToolManifest:
    name: str
    provenance_homomorphic: bool
    output_free_text: bool
    guard_pattern_compiled_pre_transform: bool


def propagate_label(
    inp: Segment,
    out_text: str,
    manifest: ToolManifest,
    decode_of_tainted: bool = False,
) -> Segment:
    # Rule 4: decode/unwrap round-trip must inherit the decoded payload's label,
    # not the default trust of a typed-primitive return.
    if decode_of_tainted and Taint.UNTRUSTED_EXTERNAL not in inp.labels:
        raise ProvenanceLaunderingError(
            f"tool {manifest.name!r} decodes a payload whose taint was not "
            "carried on the input segment; refusing to default to TRUSTED"
        )

    # Rule 1: synthesis risk — output bytes are not a function of input bytes.
    if manifest.output_free_text and not manifest.provenance_homomorphic:
        new_labels = inp.labels | {Taint.SYNTHESIZED}
        if Taint.UNTRUSTED_EXTERNAL in inp.labels:
            new_labels |= {Taint.UNTRUSTED_EXTERNAL}
        return Segment(text=out_text, labels=frozenset(new_labels))

    # Rule 2: non-homomorphic transform (encoding, truncation, entity decode).
    if not manifest.provenance_homomorphic:
        raise ProvenanceLaunderingError(
            f"tool {manifest.name!r} is not registered provenance-homomorphic; "
            "label propagation across this boundary is unsound until the "
            "transform is registered or the output is re-labeled"
        )

    # Rule 3: guard compiled against pre-transform bytes — label may be sound
    # but the enforcement surface is stale.
    if manifest.guard_pattern_compiled_pre_transform:
        raise ProvenanceLaunderingError(
            f"tool {manifest.name!r} changes the match surface; downstream guard "
            "must be re-compiled against post-transform bytes before this "
            "segment is admitted to context"
        )

    # Pure projection: faithful propagation is correct and must not over-taint.
    return Segment(text=out_text, labels=inp.labels)


def admit_to_context(seg: Segment, guard_matches: bool) -> None:
    tainted = Taint.UNTRUSTED_EXTERNAL in seg.labels
    if guard_matches and not tainted:
        raise ProvenanceLaunderingError(
            "guard fired on a segment labeled clean: label/bytes desync — "
            "the taint was laundered across a transform hop"
        )
    if tainted and not guard_matches:
        # Sound over-approximation: tainted but guard did not fire is allowed,
        # but must be routed to human/quarantine, not silently executed.
        raise ProvenanceLaunderingError(
            "tainted segment passed guard without match; quarantine required "
            "before execution"
        )
