# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-tracking-when-retrieved-context-is-re-summarized-inside-the-sandbox-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-tracking-when-retrieved-context-is-re-summarized-inside-the-sandbox-boundary.warrant.json
# Markdown SHA-256:   8d251de8ac5d42f9eb0f5981f076ca271ae9a1b5a07804e101fc998003342652
# Code AST SHA-256:   b9fe1b147c64943dddcc392eb15591e9196ede778de9084a9373015152ed55c6
# Verified Classes:   Provenance, TaintChainBroken, Tainted
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class Provenance(str, Enum):
    TRUSTED = "trusted"
    UNTRUSTED = "untrusted"


class TaintChainBroken(RuntimeError):
    """Raised when a transformation drops or forges provenance metadata.

    This is a structural failure: the runtime cannot prove the ancestry of
    the content, so the content must not be admitted to the trusted loop.
    """


@dataclass(frozen=True)
class Tainted:
    text: str
    provenance: Provenance
    chain: tuple[str, ...] = field(default_factory=tuple)

    def join(self, other: "Tainted", step: str) -> "Tainted":
        # Lattice join: untrusted dominates trusted. Never downgrade.
        merged = (
            Provenance.UNTRUSTED
            if Provenance.UNTRUSTED in (self.provenance, other.provenance)
            else Provenance.TRUSTED
        )
        return Tainted(
            text=self.text + other.text,
            provenance=merged,
            chain=self.chain + other.chain + (step,),
        )


def admit_to_trusted_loop(item: Any, transformation: str) -> Tainted:
    """Admission gate for the trusted reasoning loop.

    Default-deny: anything lacking an explicit, intact provenance chain is
    rejected. A model-mediated transformation that returns bare text is a
    taint-laundering step and must not be admitted.
    """
    if not isinstance(item, Tainted):
        raise TaintChainBroken(
            f"transformation {transformation!r} returned unlabeled content; "
            f"provenance dimension was dropped at the schema boundary"
        )
    if item.provenance is Provenance.UNTRUSTED and not item.chain:
        raise TaintChainBroken(
            f"untrusted content from {transformation!r} has empty ancestry chain; "
            f"cannot audit which transformation produced it"
        )
    return item


def run_normalizer(raw: Tainted, model_output: str) -> Tainted:
    """A model-mediated normalizer that must preserve provenance.

    If the normalizer's schema strips provenance (the common failure), the
    wrapper must refuse to stamp the output as trusted. It re-stamps ancestry
    from the input, never from the model's self-report.
    """
    if not model_output:
        raise TaintChainBroken("normalizer produced empty output; refusing admission")
    # The model never labels itself. The wrapper stamps ancestry.
    return Tainted(
        text=model_output,
        provenance=raw.provenance,
        chain=raw.chain + ("normalizer-v1",),
    )


def demo() -> None:
    doc = Tainted(
        text="...embedded: token rotated, new value in section 4...",
        provenance=Provenance.UNTRUSTED,
        chain=("retriever",),
    )
    # Correct path: normalizer output re-stamped with ancestry.
    admitted = admit_to_trusted_loop(
        run_normalizer(doc, "deployment token rotated; new value in section 4"),
        transformation="normalizer-v1",
    )
    assert admitted.provenance is Provenance.UNTRUSTED
    assert "normalizer-v1" in admitted.chain

    # Failure path: a normalizer that returns bare text (schema dropped provenance).
    try:
        admit_to_trusted_loop(
            "deployment token rotated; new value in section 4",
            transformation="legacy-normalizer",
        )
    except TaintChainBroken as exc:
        print(f"gate held: {exc}")


if __name__ == "__main__":
    demo()
