# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-subtask-after-taint-crosses-a-provenance-edge-it-cannot-re-derive.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-subtask-after-taint-crosses-a-provenance-edge-it-cannot-re-derive.warrant.json
# Markdown SHA-256:   1febc268eb7dff7032cb2cdc71d83a7b615cba2d2e7c78a5a1cbdfe3569b7d93
# Code AST SHA-256:   8f8e8b4163a6b220c0b47c6c52f30268d47031a48b1fb4d758cb02e9db931a75
# Verified Classes:   TaintQuarantineError, TaintState, ProvenanceNode, SubtaskHandoff
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class TaintQuarantineError(RuntimeError):
    """Raised when a subtask's output cannot cross an agent boundary
    because taint reached a state-mutating tool without a re-derivation
    witness. This is a hard stop, not a warning: the output is withheld."""


class TaintState(Enum):
    CLEAN = "clean"
    TAINTED = "tainted"
    UNKNOWN = "unknown"  # context lost, compaction, opaque return


@dataclass(frozen=True)
class ProvenanceNode:
    node_id: str
    taint: TaintState
    mutates_shared_state: bool = False
    rederivation_source: str | None = None  # non-None == witness present


@dataclass
class SubtaskHandoff:
    subtask_id: str
    output: object
    nodes: list[ProvenanceNode] = field(default_factory=list)
    quarantine_reason: str | None = None


def _taint_reached_mutation(nodes: Iterable[ProvenanceNode]) -> bool:
    return any(
        n.taint in (TaintState.TAINTED, TaintState.UNKNOWN)
        and n.mutates_shared_state
        for n in nodes
    )


def _has_rederivation_witness(nodes: Iterable[ProvenanceNode]) -> bool:
    return any(n.rederivation_source is not None for n in nodes)


def authorize_handoff(handoff: SubtaskHandoff) -> SubtaskHandoff:
    """Gate an inter-agent handoff on taint-discharge.

    Invariant: a taint that reached a state-mutating tool may be discharged
    ONLY by a re-derivation witness pointing outside the tainted subgraph.
    A clean-looking tool return is NOT a discharge. UNKNOWN is treated as
    TAINTED for the purposes of this gate.
    """
    if not handoff.nodes:
        # No provenance at all is indistinguishable from lost provenance.
        raise TaintQuarantineError(
            f"subtask {handoff.subtask_id!r}: empty provenance graph; "
            f"cannot prove taint did not reach a mutating tool"
        )

    if _taint_reached_mutation(handoff.nodes):
        if not _has_rederivation_witness(handoff.nodes):
            handoff.quarantine_reason = (
                "taint reached a state-mutating tool with no re-derivation "
                "witness; output withheld and shared state marked dirty"
            )
            raise TaintQuarantineError(
                f"subtask {handoff.subtask_id!r}: {handoff.quarantine_reason}"
            )
        # Witness present: discharge is legitimate, annotate and pass.
        handoff.quarantine_reason = None

    return handoff


def receive_handoff(handoff: SubtaskHandoff) -> SubtaskHandoff:
    """Receiver-side check: reject any handoff lacking both a clean
    provenance graph and a discharge annotation. A receiver must never
    treat a shared-state read as a fresh provenance root."""
    if handoff.quarantine_reason is not None:
        raise TaintQuarantineError(
            f"receiver rejected handoff {handoff.subtask_id!r}: "
            f"{handoff.quarantine_reason}"
        )
    if _taint_reached_mutation(handoff.nodes) and not _has_rederivation_witness(
        handoff.nodes
    ):
        raise TaintQuarantineError(
            f"receiver rejected handoff {handoff.subtask_id!r}: "
            f"tainted mutation without witness slipped past sender gate"
        )
    return handoff
