# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-launder-tainted-provenance-through-a-summarization-turn-that-re-emits-attacker-controlled-text-as-mod.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-launder-tainted-provenance-through-a-summarization-turn-that-re-emits-attacker-controlled-text-as-mod.warrant.json
# Markdown SHA-256:   34c1c704ab5a5ecac48b4ceaa811a47734da74eb59620ebe012854a0b2acbcb5
# Code AST SHA-256:   e9deb01e85a05f5c86405330feabfee675d5392a3a28f0b2fcb6a002da236c63
# Verified Classes:   ProvenanceLaunderingError, Span, Store
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a summarization turn would re-emit untrusted bytes under a trusted label into a sink."""

@dataclass
class Span:
    span_id: str
    label: str                      # "trusted:model" | "untrusted:external" | "untrusted:derived"
    derived_from: list[str] = field(default_factory=list)
    content: str = ""

@dataclass
class Store:
    spans: dict[str, Span] = field(default_factory=dict)

    def lineage(self, span_id: str, seen: Optional[set] = None) -> set[str]:
        seen = seen or set()
        if span_id in seen:
            return seen
        seen.add(span_id)
        for parent in self.spans[span_id].derived_from:
            self.lineage(parent, seen)
        return seen

    def is_tainted(self, span_id: str) -> bool:
        return any(self.spans[s].label.startswith("untrusted") for s in self.lineage(span_id))

PAYLOAD_MARKERS = ("@", "http://", "https://", "api_key", "token=", "forward")

def guard_sink(store: Store, span_id: str, sink: str) -> None:
    span = store.spans[span_id]
    if not store.is_tainted(span_id):
        return
    # Tainted lineage reaching a sink is only permitted if the actionable payload
    # did not survive the transformation. If it did, this is laundering.
    survived = [m for m in PAYLOAD_MARKERS if m in span.content.lower()]
    if survived:
        raise ProvenanceLaunderingError(
            f"span {span_id} reaches sink '{sink}' with tainted lineage "
            f"{sorted(store.lineage(span_id))} and surviving payload markers {survived}; "
            f"redact before emit or route to quarantined channel"
        )
    # Meta-commentary / redacted summary: allowed, but must be annotated downstream.
    span.label = span.label  # unchanged; caller records references_untrusted=True

def summarize(store: Store, turn_id: str, input_span_ids: list[str], text: str) -> Span:
    # The summarizer MUST declare lineage; emitter identity alone is not a trust grant.
    if not input_span_ids:
        raise ProvenanceLaunderingError(
            f"turn {turn_id} summarized untrusted context without declaring derived_from"
        )
    span = Span(span_id=f"{turn_id}:out", label="trusted:model",
                derived_from=list(input_span_ids), content=text)
    store.spans[span.span_id] = span
    return span
