# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-quarantine-taint-provenance-when-a-tool-boundary-strips-structured-labels-from-injected-content.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-quarantine-taint-provenance-when-a-tool-boundary-strips-structured-labels-from-injected-content.warrant.json
# Markdown SHA-256:   7482963241f0a3aa436d84e296a2fd9b26e420540fcb974f3e267f4edf0da6ef
# Code AST SHA-256:   eac4406f050360f8837b6f6e53d5da781fa2fa70d87b76eb5bbf9d0667627ecc
# Verified Classes:   ProvenanceLaunderingError, TaintRecord, ToolReturn, CallRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a tool return's provenance is absent, inconsistent with
    the call-graph record, or claims trust over tainted ancestry."""


@dataclass
class TaintRecord:
    taint_id: str
    source: str
    trusted: bool = False


@dataclass
class ToolReturn:
    content: str
    provenance: Optional[TaintRecord] = None
    self_reported_trusted: bool = False


@dataclass
class CallRecord:
    tool_name: str
    input_taint: list[TaintRecord] = field(default_factory=list)


def gate_tool_return(call: CallRecord, ret: ToolReturn) -> TaintRecord:
    """Authoritative provenance derivation: ancestry from call graph wins.

    Fail-closed: missing provenance on a tainted call is laundering, not trust.
    """
    input_tainted = any(not t.trusted for t in call.input_taint)

    if input_tainted:
        # Descendant propagation: any tainted input taints the return.
        if ret.provenance is None:
            raise ProvenanceLaunderingError(
                f"tool={call.tool_name} returned content with no provenance "
                f"field but was invoked with tainted input "
                f"{[t.taint_id for t in call.input_taint]}; "
                f"refusing default-trust fallback"
            )
        if ret.provenance.trusted or ret.self_reported_trusted:
            raise ProvenanceLaunderingError(
                f"tool={call.tool_name} claims trusted provenance "
                f"({ret.provenance.taint_id}) over tainted ancestry "
                f"{[t.taint_id for t in call.input_taint]}; "
                f"quarantine and log taint-integrity violation"
            )
        # Propagate the first taint_id as the descendant's ancestry marker.
        return TaintRecord(
            taint_id=call.input_taint[0].taint_id,
            source=f"derived:{call.tool_name}",
            trusted=False,
        )

    # Clean call: accept tool's provenance if present, else default trusted.
    if ret.provenance is not None:
        return ret.provenance
    return TaintRecord(taint_id=f"clean:{call.tool_name}", source=call.tool_name, trusted=True)


def require_privileged_action(record: TaintRecord, action: str) -> None:
    """Gate a privileged action on provenance; tainted content cannot trigger it."""
    if not record.trusted:
        raise ProvenanceLaunderingError(
            f"privileged action '{action}' blocked: content carries taint "
            f"{record.taint_id} from {record.source}; "
            f"requires explicit declassification with logged taint_id"
        )
