# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-quarantine-tainted-tool-output-when-provenance-labels-are-lost-across-a-re-entrant-mcp-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-quarantine-tainted-tool-output-when-provenance-labels-are-lost-across-a-re-entrant-mcp-call-boundary.warrant.json
# Markdown SHA-256:   ba95736a2907a80d434dbaf28b7f272ae44e93d7a8d6c81aec801b5d776a8a5c
# Code AST SHA-256:   21cd23c140afca90908f5731ed63860fff74c090981ba63023d8beac58a79884
# Verified Classes:   TaintLevel, TaintLaunderingError, UnattributableResultError, Envelope, LedgerEntry, TaintLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from enum import IntEnum
from typing import Optional


class TaintLevel(IntEnum):
    CLEAN = 0
    UNTRUSTED = 1

    def join(self, other: "TaintLevel") -> "TaintLevel":
        return TaintLevel(max(self.value, other.value))


class TaintLaunderingError(RuntimeError):
    """Raised when a tool result would lower taint below its ledger ancestor."""


class UnattributableResultError(RuntimeError):
    """Raised when a result's chain-id cannot be bound to an outbound call."""


@dataclass
class Envelope:
    chain_id: str
    taint: TaintLevel
    hop: int


@dataclass
class LedgerEntry:
    taint: TaintLevel
    hop: int


@dataclass
class TaintLedger:
    entries: dict[str, LedgerEntry] = field(default_factory=dict)
    issued_chain_ids: set[str] = field(default_factory=set)

    def mint(self, chain_id: str, parent: Optional[str]) -> str:
        self.issued_chain_ids.add(chain_id)
        parent_taint = TaintLevel.CLEAN
        parent_hop = 0
        if parent is not None:
            pe = self.entries.get(parent)
            if pe is None:
                raise UnattributableResultError(
                    f"parent chain {parent!r} not in ledger; cannot reconcile {chain_id!r}"
                )
            parent_taint, parent_hop = pe.taint, pe.hop
        self.entries[chain_id] = LedgerEntry(parent_taint, parent_hop + 1)
        return chain_id

    def reconcile(self, env: Envelope) -> LedgerEntry:
        if env.chain_id not in self.issued_chain_ids:
            raise UnattributableResultError(
                f"result chain_id {env.chain_id!r} was never minted by this instance"
            )
        prior = self.entries.get(env.chain_id)
        if prior is None:
            raise UnattributableResultError(
                f"no ledger entry for minted chain {env.chain_id!r}"
            )
        # Taint is monotonic: envelope may only *raise*, never lower.
        effective_taint = prior.taint.join(env.taint)
        if env.taint < prior.taint:
            raise TaintLaunderingError(
                f"envelope taint {env.taint.name} < ledger taint {prior.taint.name} "
                f"on chain {env.chain_id!r}; refusing to admit result"
            )
        effective_hop = max(prior.hop, env.hop)
        self.entries[env.chain_id] = LedgerEntry(effective_taint, effective_hop)
        return self.entries[env.chain_id]


def admit_tool_result(
    ledger: TaintLedger,
    env: Envelope,
    side_effecting: bool,
    trust_after_hops: int = 3,
) -> bool:
    entry = ledger.reconcile(env)
    if side_effecting and entry.taint is TaintLevel.UNTRUSTED:
        return False  # quarantine; do not place in context for side-effecting use
    if entry.taint is TaintLevel.UNTRUSTED and entry.hop < trust_after_hops:
        return False
    return True
