# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-taint-provenance-correlation-when-a-downstream-tool-call-launders-injected-content-through-a-summarizer.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-taint-provenance-correlation-when-a-downstream-tool-call-launders-injected-content-through-a-summarizer.warrant.json
# Markdown SHA-256:   3c46240603f62d19297e5ac5b577a8584c02e8bf06932452daaa74e0571344f4
# Code AST SHA-256:   6e211fc3a835dd667a3790efba042cbfd33a2b2a6d607c7459c019ce12101c99
# Verified Classes:   TaintLabel, ProvenanceLaunderingError, ContextObject, TransformInvocation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class TaintLabel(Enum):
    TRUSTED = "trusted"
    UNTRUSTED = "untrusted"
    TAINT_INHERITED = "taint_inherited"


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a generative transform attempts to clear taint it cannot prove declassified."""


@dataclass(frozen=True)
class ContextObject:
    object_id: str
    taint: TaintLabel
    reentry_surface: bool  # True if output is free-text that re-enters agent context


@dataclass(frozen=True)
class TransformInvocation:
    transform_id: str
    is_generative: bool
    emits_free_text: bool
    inputs: FrozenSet[ContextObject] = field(default_factory=frozenset)


def assign_output_taint(inv: TransformInvocation, output: ContextObject) -> ContextObject:
    """
    Compute the taint label for a transform's output object.
    Fails closed if the transform would clear taint without a declassification proof.
    """
    input_taints = {i.taint for i in inv.inputs}
    any_untrusted = TaintLabel.UNTRUSTED in input_taints or TaintLabel.TAINT_INHERITED in input_taints

    # Declassification is only legitimate for schema-constrained, non-free-text transforms.
    declassifiable = (not inv.emits_free_text) and (not inv.is_generative)

    if any_untrusted and not declassifiable:
        # Generative free-text transform on tainted input: must inherit, never clear.
        if output.taint == TaintLabel.TRUSTED:
            raise ProvenanceLaunderingError(
                f"transform {inv.transform_id!r} emitted TRUSTED output {output.object_id!r} "
                f"from tainted inputs {[i.object_id for i in inv.inputs]}; "
                f"generative free-text transforms must inherit taint"
            )
        return ContextObject(
            object_id=output.object_id,
            taint=TaintLabel.TAINT_INHERITED,
            reentry_surface=output.reentry_surface,
        )

    return output


def correlate_taint_to_action(action_object_id: str, graph: dict[str, set[str]],
                              labels: dict[str, TaintLabel]) -> bool:
    """
    Return True if any tainted ancestor reaches the action object.
    Traverses generative-transform edges as taint-preserving.
    """
    seen: set[str] = set()
    stack = [action_object_id]
    while stack:
        node = stack.pop()
        if node in seen:
            continue
        seen.add(node)
        if labels.get(node) in (TaintLabel.UNTRUSTED, TaintLabel.TAINT_INHERITED) and node != action_object_id:
            return True
        for parent in graph.get(node, set()):
            stack.append(parent)
    return False
