# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-mcp-tool-result-before-it-enters-the-reasoning-trace-and-why-post-hoc-redaction-fails.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-mcp-tool-result-before-it-enters-the-reasoning-trace-and-why-post-hoc-redaction-fails.warrant.json
# Markdown SHA-256:   5d0ff9e16cf7ff8c65a9b0f8ab9396ba23bfb6fab34a3ae27869cde25bafbc70
# Code AST SHA-256:   035bf8b2ab913ead73f3f0ac11d6ea80e091dec1cdece1b3acd1cbdb0f4cd306
# Verified Classes:   TaintLabel, TaintViolation, Span, ContextSlice
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class TaintLabel(Enum):
    UNTAINTED = "untainted"
    TAINTED = "tainted"
    SECRET = "secret"


class TaintViolation(RuntimeError):
    """Raised when a tainted span would share a context slice with a secret."""


@dataclass(frozen=True)
class Span:
    content: str
    labels: FrozenSet[TaintLabel]


@dataclass
class ContextSlice:
    spans: list = field(default_factory=list)

    def admit(self, span: Span) -> None:
        # Invariant: a slice may not contain both TAINTED and SECRET spans.
        existing = {lab for s in self.spans for lab in s.labels}
        incoming = set(span.labels)
        if TaintLabel.TAINTED in existing and TaintLabel.SECRET in incoming:
            raise TaintViolation(
                "refusing to admit SECRET span into slice already holding TAINTED span"
            )
        if TaintLabel.SECRET in existing and TaintLabel.TAINTED in incoming:
            raise TaintViolation(
                "refusing to admit TAINTED span into slice already holding SECRET span"
            )
        self.spans.append(span)


def ingest_mcp_result(raw: str, server_trusted: bool, has_secret: bool) -> Span:
    if not server_trusted:
        return Span(raw, frozenset({TaintLabel.TAINTED}))
    if has_secret:
        # A trusted server may still surface a secret; label it so the slice
        # invariant fires if a tainted span is later admitted alongside it.
        return Span(raw, frozenset({TaintLabel.SECRET}))
    return Span(raw, frozenset({TaintLabel.UNTAINTED}))


def build_reasoning_context(untrusted_page: str, secret: str) -> ContextSlice:
    slice_ = ContextSlice()
    slice_.admit(ingest_mcp_result(secret, server_trusted=True, has_secret=True))
    # This admission must raise: the untrusted page cannot co-reside with the secret.
    slice_.admit(ingest_mcp_result(untrusted_page, server_trusted=False, has_secret=False))
    return slice_
