# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-re-admit-a-sandboxed-tool-output-that-the-injection-classifier-has-already-cleared-on-a-second-pass.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-re-admit-a-sandboxed-tool-output-that-the-injection-classifier-has-already-cleared-on-a-second-pass.warrant.json
# Markdown SHA-256:   556ccf987adac1843f23b14551bd5569e7511e9e8accd45fcabb9b14d51eedc2
# Code AST SHA-256:   5d27cc0345b294b6365b7839fdd081302ecefc603dc43599fde9d3724c0ae98d
# Verified Classes:   TaintReAdmissionError, OutputNode, TaintSandbox
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Literal

Verdict = Literal["clean", "flagged"]
Provenance = Literal["clean", "tainted", "unknown"]


class TaintReAdmissionError(RuntimeError):
    """Raised when a quarantined tool output is about to be re-admitted unsoundly."""


@dataclass
class OutputNode:
    node_id: str
    verdict: Verdict
    provenance: Provenance
    parents: list[str] = field(default_factory=list)
    re_pass_count: int = 0


class TaintSandbox:
    def __init__(self, threshold: float = 0.80) -> None:
        self.threshold = threshold
        self.nodes: dict[str, OutputNode] = {}

    def register(self, node: OutputNode) -> None:
        # Provenance is inherited from parents at registration time.
        if node.provenance == "clean":
            for pid in node.parents:
                parent = self.nodes.get(pid)
                if parent is None or parent.provenance in ("tainted", "unknown"):
                    node.provenance = "tainted"
                    break
        self.nodes[node.node_id] = node

    def request_readmission(
        self, node_id: str, second_verdict: Verdict, same_classifier_config: bool
    ) -> bool:
        node = self.nodes.get(node_id)
        if node is None:
            raise TaintReAdmissionError(f"unknown node {node_id!r}")

        # Hard gate: provenance is consulted before the classifier verdict.
        if node.provenance in ("tainted", "unknown"):
            raise TaintReAdmissionError(
                f"node {node_id!r} has {node.provenance!r} provenance; "
                f"classifier verdict {second_verdict!r} is not clearance evidence"
            )

        if not same_classifier_config:
            raise TaintReAdmissionError(
                f"node {node_id!r} re-classified under a different config; "
                "verdict flip is not attributable to sampling"
            )

        if second_verdict == "flagged":
            return False  # stays quarantined

        # Clean provenance + clean second verdict: allow exactly one re-pass.
        if node.re_pass_count >= 1:
            raise TaintReAdmissionError(
                f"node {node_id!r} exceeded single re-pass cap on clean provenance"
            )
        node.re_pass_count += 1
        return True
