# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-across-a-multi-hop-tool-graph-when-a-laundering-agent-re-serializes-intermediate-state.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-across-a-multi-hop-tool-graph-when-a-laundering-agent-re-serializes-intermediate-state.warrant.json
# Markdown SHA-256:   53a10ae0ae8cfd16e6e0429ea832f0e66ce099c709a76d518389aa7259b6fbd7
# Code AST SHA-256:   2d228c1a2bb649f793ec5cfd63c4148e14c9cb6f0545a82ea46c1321c6e5f13f
# Verified Classes:   TaintProvenanceError, Taint, Artifact
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class TaintProvenanceError(RuntimeError):
    """Raised when a hop violates the taint-preservation invariant."""
    pass


@dataclass(frozen=True)
class Taint:
    source: str          # "external" | "internal"
    sensitivity: str     # "low" | "high"
    derived_from: tuple[str, ...] = field(default_factory=tuple)

    def join(self, other: "Taint") -> "Taint":
        order = {"low": 0, "high": 1}
        src = "external" if "external" in (self.source, other.source) else "internal"
        sens = max(self.sensitivity, other.sensitivity, key=lambda s: order[s])
        return Taint(source=src, sensitivity=sens,
                     derived_from=self.derived_from + other.derived_from)


@dataclass(frozen=True)
class Artifact:
    payload: str
    taint: Taint
    emitter: str
    transform: str       # "passthrough" | "generative" | "certified"
    signature: str


def digest(art: Artifact) -> str:
    return hashlib.sha256((art.payload + art.emitter).encode()).hexdigest()


def propagate(art: Artifact, inputs: list[Artifact],
              registered_keys: dict[str, str]) -> Artifact:
    # 1. Signature must verify against the emitter's registered identity.
    expected = registered_keys.get(art.emitter)
    if expected is None or art.signature != expected:
        raise TaintProvenanceError(
            f"unregistered or spoofed emitter {art.emitter!r}")

    # 2. A generative hop may NOT reset taint; it must inherit the join.
    if art.transform == "generative":
        inherited = inputs[0].taint
        for i in inputs[1:]:
            inherited = inherited.join(i.taint)
        if art.taint.sensitivity != inherited.sensitivity or \
           art.taint.source != inherited.source:
            raise TaintProvenanceError(
                f"taint re-origination at hop by {art.emitter}: "
                f"emitted {art.taint.sensitivity}/{art.taint.source}, "
                f"required {inherited.sensitivity}/{inherited.source}")
        # 3. Ancestry must be present and point at the actual inputs.
        actual = tuple(digest(i) for i in inputs)
        if not set(actual).issubset(set(art.taint.derived_from)):
            raise TaintProvenanceError(
                f"broken ancestry at {art.emitter}: derived_from missing input digests")
        return art

    if art.transform == "passthrough":
        return art  # envelope copied verbatim; nothing to check

    # certified transform: caller must have declared preservation explicitly
    if art.transform != "certified":
        raise TaintProvenanceError(f"unknown transform {art.transform!r}")
    return art


def sink_action(art: Artifact, declassification_warrant: Optional[str]) -> str:
    if art.taint.source == "external" and art.taint.sensitivity == "high":
        if declassification_warrant is None:
            raise TaintProvenanceError(
                "refusing privileged action on undeclassified external taint")
    return "executed"
