# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-tainted-provenance-across-tool-call-and-memory-write-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-tainted-provenance-across-tool-call-and-memory-write-boundaries.warrant.json
# Markdown SHA-256:   eb9197d73e78f50eb05f90df4821180c42f9e3b9c9bb514f74ed910d64d1c3f6
# Code AST SHA-256:   39fc48d0c76c1117f2641723394d571ac393d92e1a012eeaface6e157ecbd615
# Verified Classes:   TaintClass, Span, TaintLaunderingError, DeclassificationContract
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class TaintClass(str, Enum):
    UNTRUSTED_INSTRUCTION = "untrusted_instruction"
    EXTERNAL_CONTENT = "external_content"


@dataclass(frozen=True)
class Span:
    span_id: str
    provenance: str
    taint: frozenset[TaintClass] = field(default_factory=frozenset)


class TaintLaunderingError(RuntimeError):
    """Raised when a boundary would drop taint without a verified declassification contract."""


@dataclass(frozen=True)
class DeclassificationContract:
    tool_id: str
    removes: frozenset[TaintClass]
    mechanism: str  # must be non-empty and auditable


# Tools that are NOT declassifiers by default. A tool only appears here if it
# carries a signed contract naming the taint class it removes and the mechanism.
DECLASSIFIERS: dict[str, DeclassificationContract] = {
    "strict_schema_parse": DeclassificationContract(
        tool_id="strict_schema_parse",
        removes=frozenset({TaintClass.EXTERNAL_CONTENT}),
        mechanism="drops all free-text fields, retains only typed enum/int fields",
    ),
}


def propagate_taint(
    tool_id: str,
    inputs: Iterable[Span],
) -> frozenset[TaintClass]:
    """Dependency-based taint: union of input taints minus verified declassification."""
    union: set[TaintClass] = set()
    for span in inputs:
        union |= span.taint

    contract = DECLASSIFIERS.get(tool_id)
    if contract is not None:
        if not contract.mechanism:
            raise TaintLaunderingError(
                f"declassifier {tool_id!r} has empty mechanism; contract invalid"
            )
        union -= contract.removes
    # If no contract, union is returned unchanged: monotonic inheritance.
    return frozenset(union)


def make_tool_output(
    tool_id: str,
    inputs: Iterable[Span],
    output_text: str,
) -> Span:
    inherited = propagate_taint(tool_id, inputs)
    return Span(
        span_id=f"out:{tool_id}",
        provenance=f"tool:{tool_id}",
        taint=inherited,
    )


def promote_to_trusted_context(span: Span, declassification_log: dict[str, str]) -> Span:
    """Gate for entry into trusted context / durable trusted store."""
    if not span.taint:
        return span
    # A tainted span may only be promoted if a declassification contract was
    # actually applied and logged for every taint class it still carries.
    for taint_class in span.taint:
        if taint_class.value not in declassification_log:
            raise TaintLaunderingError(
                f"refusing to promote span {span.span_id!r} to trusted context: "
                f"taint class {taint_class.value!r} not declassified; "
                f"quarantine required"
            )
    return span


def memory_write(span: Span, declassification_log: dict[str, str]) -> Span:
    """Durable store: same gate as trusted-context promotion; taint must persist."""
    if span.taint:
        # Persist with taint intact; never relabel by emitter.
        return Span(
            span_id=f"mem:{span.span_id}",
            provenance=f"memory:{span.provenance}",
            taint=span.taint,
        )
    return promote_to_trusted_context(span, declassification_log)


if __name__ == "__main__":
    user_turn = Span("span_A", "user", frozenset({TaintClass.UNTRUSTED_INSTRUCTION}))

    # summarize is NOT a declassifier: output inherits the input taint.
    summary = make_tool_output("summarize", [user_turn], "…injected text…")
    assert summary.taint == frozenset({TaintClass.UNTRUSTED_INSTRUCTION})

    # Writing to memory preserves taint (no laundering).
    stored = memory_write(summary, declassification_log={})
    assert stored.taint == frozenset({TaintClass.UNTRUSTED_INSTRUCTION})

    # Attempting to promote the tainted memory into trusted context must fail.
    try:
        promote_to_trusted_context(stored, declassification_log={})
    except TaintLaunderingError as exc:
        print(f"blocked as expected: {exc}")
    else:
        raise TaintLaunderingError("tainted span reached trusted context; invariant violated")
