# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-tool-result-is-summarized-before-re-injection-into-the-reasoning-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-tool-result-is-summarized-before-re-injection-into-the-reasoning-loop.warrant.json
# Markdown SHA-256:   f36250b01dd643b013668e84fabce82207607c32eb6410a9570a21ea2e76ad18
# Code AST SHA-256:   d6378e326020ca5d18beff5ed73207df3687d61c622abe44e85bd16fe9abe402
# Verified Classes:   TaintLaunderingError, ContextObject
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a derived context object loses the taint of its sources."""


@dataclass(frozen=True)
class ContextObject:
    content: str
    sources: FrozenSet[str] = field(default_factory=frozenset)  # tainted source ids
    derivation: str = "raw"  # "raw" | "truncate" | "summarize" | "extract"

    @property
    def is_tainted(self) -> bool:
        return len(self.sources) > 0


def summarize_with_provenance(
    source: ContextObject,
    summary_text: str,
    summarizer_reported_sources: FrozenSet[str] | None,
) -> ContextObject:
    """
    Build a derived context object from a generative transform.
    The summarizer must either report its sources or the runtime
    unions all inputs. It may never silently drop taint.
    """
    if summarizer_reported_sources is None:
        # Safe default: generative transform over unknown provenance
        # inherits the full taint of its input.
        derived_sources = source.sources
    else:
        # Union reported sources with the input's taint. Monotonic.
        derived_sources = source.sources | summarizer_reported_sources

    derived = ContextObject(
        content=summary_text,
        sources=derived_sources,
        derivation="summarize",
    )

    # Invariant check: derived taint must be a superset of source taint.
    if not (source.sources <= derived.sources):
        raise TaintLaunderingError(
            f"derived object lost taint: source={sorted(source.sources)} "
            f"derived={sorted(derived.sources)}"
        )
    return derived


def authorize_privileged_call(
    active_context: list[ContextObject],
    capability: str,
    clean_required: bool = True,
) -> None:
    """
    Policy gate: deny privileged dispatch if any reachable context
    object is tainted. Never consult the model's own judgment here.
    """
    if not clean_required:
        return
    reachable_taint = set().union(*(c.sources for c in active_context))
    if reachable_taint:
        raise TaintLaunderingError(
            f"denied {capability}: tainted sources reachable in context "
            f"{sorted(reachable_taint)}"
        )
