# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-validate-taint-at-a-federation-boundary-and-why-does-provenance-metadata-alone-fail.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-validate-taint-at-a-federation-boundary-and-why-does-provenance-metadata-alone-fail.warrant.json
# Markdown SHA-256:   52dd07d863fed727bc924c18cca05316e16b443e21ed18db06ef5bd3c4ce19f1
# Code AST SHA-256:   4619b11c097d41f1f4d6e1d46eb1f386fb200b85acdf665ed87f5496734d60c5
# Verified Classes:   Taint, TaintDowngradeError, Field, HandoffEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class Taint(IntEnum):
    TRUSTED = 0
    DERIVED = 1
    EXTERNAL_UNTRUSTED = 2


class TaintDowngradeError(RuntimeError):
    """Raised when a hop emits a field with taint lower than its inputs, absent a warrant."""


@dataclass
class Field:
    name: str
    value: str
    taint: Taint
    model_generated: bool = False
    warrant: Optional[str] = None


@dataclass
class HandoffEnvelope:
    fields: list[Field] = field(default_factory=list)


def merge_model_output(
    inputs: list[Field],
    output: Field,
    hop_id: str,
) -> Field:
    """Enforce label monotonicity at the generation boundary.

    The output field must not be less tainted than the max input taint
    unless an explicit declassification warrant is attached.
    """
    if not output.model_generated:
        # Verbatim-carried fields must preserve taint exactly.
        if inputs and output.taint < max(f.taint for f in inputs):
            raise TaintDowngradeError(
                f"hop={hop_id} field={output.name}: verbatim carry downgraded "
                f"taint {output.taint.name} below input max"
            )
        return output

    input_taint = max((f.taint for f in inputs), default=Taint.TRUSTED)
    if output.taint >= input_taint:
        return output

    if output.warrant is None:
        raise TaintDowngradeError(
            f"hop={hop_id} field={output.name}: model-generated output "
            f"downgraded taint {input_taint.name} -> {output.taint.name} "
            f"with no declassification warrant"
        )
    # Warrant present: downgrade is attributable and logged upstream.
    return output


def executor_gate(envelope: HandoffEnvelope, high_authority_action: bool) -> None:
    for f in envelope.fields:
        if high_authority_action and f.taint >= Taint.EXTERNAL_UNTRUSTED:
            raise TaintDowngradeError(
                f"executor refused high-authority action on field={f.name} "
                f"taint={f.taint.name}; quarantine to read-only"
            )


# Reproduces the observed failure: planner summarizes tainted doc, emits clean summary.
inputs = [Field("doc", "...transfer to acct X...", Taint.EXTERNAL_UNTRUSTED)]
bad_summary = Field("summary", "Document requests a transfer", Taint.DERIVED, model_generated=True)
merge_model_output(inputs, bad_summary, hop_id="planner->executor")  # raises
