# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-prompt-injection-taint-label-through-a-summarization-tool-and-re-ingests-it-as-trusted-context.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-prompt-injection-taint-label-through-a-summarization-tool-and-re-ingests-it-as-trusted-context.warrant.json
# Markdown SHA-256:   a055e01bcbbe3b726bc72d037e87cce43b81c2bd5ba275f0703e93f46081c5c7
# Code AST SHA-256:   93eb7de1984d573f5d0d8bade03f0fb85151a394b920078e19ad4148979bb478
# Verified Classes:   TaintLaunderingError, Taint, TaintBehavior, Span, LedgerEntry, ToolManifest, DeclassificationLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class TaintLaunderingError(RuntimeError):
    """Raised when a derived artifact carries lower taint than its inputs
    without a ledgered, deterministically-verified declassification."""


class Taint(Enum):
    TRUSTED = 0
    UNTRUSTED = 1

    def union(self, other: "Taint") -> "Taint":
        return Taint(max(self.value, other.value))


class TaintBehavior(Enum):
    PROPAGATE = "propagate"   # output taint = union of input taints
    SANITIZE = "sanitize"     # downgrade allowed only with a verifier
    GENERATE = "generate"     # output taint from trusted params only


@dataclass(frozen=True)
class Span:
    text: str
    taint: Taint
    lineage: str


@dataclass(frozen=True)
class LedgerEntry:
    lineage: str
    frm: Taint
    to: Taint
    justification: str
    verifier: str  # must be a deterministic check, not a model judgment


@dataclass
class ToolManifest:
    name: str
    taint_behavior: TaintBehavior
    # For SANITIZE tools: a deterministic predicate over the output text.
    verifier: str | None = None


@dataclass
class DeclassificationLedger:
    entries: list[LedgerEntry] = field(default_factory=list)

    def record(self, entry: LedgerEntry) -> None:
        self.entries.append(entry)

    def has_verified_downgrade(self, lineage: str) -> bool:
        return any(
            e.lineage == lineage and e.to is Taint.TRUSTED and e.verifier
            for e in self.entries
        )


def summarize_spans(spans: Iterable[Span], manifest: ToolManifest,
                    ledger: DeclassificationLedger) -> Span:
    """Simulate an LLM summarization tool returning a single span.

    The bug this guards against: the tool re-emits input-derived text but
    the orchestrator would otherwise stamp the result TRUSTED because it
    came back through the 'tool result' channel.
    """
    spans = list(spans)
    if not spans:
        raise TaintLaunderingError("summarize called with no input spans")

    input_taint = Taint.TRUSTED
    for s in spans:
        input_taint = input_taint.union(s.taint)

    # A summarizer is an LLM call; its output is free-form model text and
    # therefore cannot claim SANITIZE without a deterministic verifier.
    if manifest.taint_behavior is TaintBehavior.SANITIZE:
        if manifest.verifier is None:
            raise TaintLaunderingError(
                f"tool {manifest.name!r} claims SANITIZE with no verifier; "
                "free-form LLM output cannot declassify taint"
            )
        # Verifier would run here; if it fails, taint is not downgraded.
        output_taint = Taint.TRUSTED if _run_verifier(manifest.verifier, spans) else input_taint
    elif manifest.taint_behavior is TaintBehavior.PROPAGATE:
        output_taint = input_taint
    else:  # GENERATE
        output_taint = Taint.TRUSTED

    lineage = "|".join(sorted({s.lineage for s in spans}))
    result = Span(text="<summary>", taint=output_taint, lineage=lineage)

    # Invariant: no silent downgrade. If output is cleaner than input,
    # a ledgered, verified declassification must exist.
    if output_taint.value < input_taint.value:
        if not ledger.has_verified_downgrade(lineage):
            raise TaintLaunderingError(
                f"silent taint downgrade on lineage {lineage!r}: "
                f"{input_taint.name} -> {output_taint.name} with no "
                "verified declassification ledger entry"
            )
    return result


def _run_verifier(name: str, spans: list[Span]) -> bool:
    # Placeholder for a deterministic check (schema match, signed allowlist).
    return False


def write_authoritative_field(field_name: str, value: str, span: Span,
                              ledger: DeclassificationLedger) -> None:
    """Authoritative writes require a clean lineage or a verified downgrade."""
    if span.taint is Taint.UNTRUSTED:
        raise TaintLaunderingError(
            f"refusing to write authoritative field {field_name!r} from "
            f"UNTRUSTED span (lineage {span.lineage!r})"
        )
    if span.taint is Taint.TRUSTED and not ledger.has_verified_downgrade(span.lineage):
        # TRUSTED span with no ledgered declassification: it may have been
        # laundered. Require the lineage to be natively trusted.
        if span.lineage and "web" in span.lineage:
            raise TaintLaunderingError(
                f"authoritative field {field_name!r} sourced from web lineage "
                f"{span.lineage!r} without a ledgered declassification"
            )
    # write would happen here
