# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-tool-output-as-tainted-the-label-laundering-failure-at-the-context-window-compaction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-tool-output-as-tainted-the-label-laundering-failure-at-the-context-window-compaction-boundary.warrant.json
# Markdown SHA-256:   d4eecfb743c7d082a11e29bb71afb1456d4746440a5fc95c61d02a789448c7ec
# Code AST SHA-256:   7d5e817f99a51518bc28c2a88013fa51b93914af84a0cad607624dcb6013e33a
# Verified Classes:   Taint, TaintLaunderingError, Record
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


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


class TaintLaunderingError(RuntimeError):
    """Raised when a derivation step would produce a record with unset taint."""


@dataclass(frozen=True)
class Record:
    record_id: str
    content: str
    taint: Taint
    provenance: tuple[str, ...] = ()


def derive_summary(
    summary_id: str,
    summary_text: str,
    source_ids: Iterable[str],
    registry: dict[str, Record],
) -> Record:
    """Create a context_summary record, enforcing the taint-inheritance invariant.

    The summary's taint is the union of its sources' taints. A summary with
    no resolvable provenance is rejected: unknown provenance is untrusted,
    and an untrusted summary must never be silently promoted to TRUSTED.
    """
    src = list(source_ids)
    if not src:
        raise TaintLaunderingError(
            f"summary {summary_id!r} has empty provenance; "
            "cannot compute taint, refusing to write TRUSTED-by-default record"
        )

    missing = [sid for sid in src if sid not in registry]
    if missing:
        raise TaintLaunderingError(
            f"summary {summary_id!r} references unknown sources {missing}; "
            "provenance closure is incomplete"
        )

    inherited = Taint.TRUSTED
    for sid in src:
        if registry[sid].taint is Taint.UNTRUSTED:
            inherited = Taint.UNTRUSTED
            break

    return Record(
        record_id=summary_id,
        content=summary_text,
        taint=inherited,
        provenance=tuple(src),
    )


def authorize_action(evidence: Record, registry: dict[str, Record]) -> None:
    """Allow a side-effecting action only if the full provenance closure is TRUSTED."""
    seen: set[str] = set()
    stack = [evidence.record_id]
    while stack:
        rid = stack.pop()
        if rid in seen:
            continue
        seen.add(rid)
        rec = registry.get(rid)
        if rec is None:
            raise TaintLaunderingError(f"provenance closure missing record {rid!r}")
        if rec.taint is Taint.UNTRUSTED:
            raise TaintLaunderingError(
                f"blocked: action derived from untrusted record {rid!r} "
                f"(closure={sorted(seen)})"
            )
        stack.extend(rec.provenance)
