# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-taint-quarantine-at-the-memory-write-boundary-when-a-trusted-tool-re-emits-untrusted-content.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-taint-quarantine-at-the-memory-write-boundary-when-a-trusted-tool-re-emits-untrusted-content.warrant.json
# Markdown SHA-256:   6f6f433abe0def45b5e92462a036b3769355056ddec131298d10619800f512dc
# Code AST SHA-256:   8eae60a266be56f4d9b5a46dd9128e616ede9f2b99278c37357bca72110f3f33
# Verified Classes:   Taint, TaintLaunderingError, Provenance, ToolCall
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class Taint(Enum):
    CLEAN = "clean"
    TAINTED = "tainted"


class TaintLaunderingError(RuntimeError):
    """Raised when a CLEAN annotation is requested for output whose
    provenance set contains TAINTED elements and no declared sanitizer
    is in the path."""


@dataclass(frozen=True)
class Provenance:
    sources: FrozenSet[str]
    taint: Taint


@dataclass
class ToolCall:
    tool: str
    trust_level: Taint
    reads_external_state: bool = False
    sanitizer_fields: Optional[FrozenSet[str]] = None  # None => not a sanitizer


def compute_output_taint(
    call: ToolCall,
    input_provenance: Provenance,
    store_has_tainted_rows: bool,
) -> Provenance:
    """Taint Propagation Invariant: output taint is a join over inputs,
    OR'd with external-state reads that may touch tainted rows."""
    sources = set(input_provenance.sources) | {call.tool}
    tainted = input_provenance.taint is Taint.TAINTED

    if call.reads_external_state and store_has_tainted_rows:
        tainted = True

    if tainted and call.sanitizer_fields is not None:
        # Declassification is permitted only through a declared, field-scoped
        # sanitizer. Free-text tools (sanitizer_fields is None) cannot declassify.
        return Provenance(sources=frozenset(sources), taint=Taint.CLEAN)

    return Provenance(
        sources=frozenset(sources),
        taint=Taint.TAINTED if tainted else Taint.CLEAN,
    )


def annotate_memory_write(
    call: ToolCall,
    input_provenance: Provenance,
    store_has_tainted_rows: bool,
    requested_taint: Taint,
) -> Provenance:
    computed = compute_output_taint(call, input_provenance, store_has_tainted_rows)

    if requested_taint is Taint.CLEAN and computed.taint is Taint.TAINTED:
        raise TaintLaunderingError(
            f"tool '{call.tool}' requested CLEAN annotation but provenance "
            f"{sorted(computed.sources)} is TAINTED and no field-scoped "
            f"sanitizer is declared; refusing primary-namespace write"
        )

    return computed


# Incident replay: summarize_document over a web_fetch-tainted document.
fetched = Provenance(sources=frozenset({"web_fetch"}), taint=Taint.TAINTED)
summarizer = ToolCall(
    tool="summarize_document",
    trust_level=Taint.CLEAN,       # trusted tool — the source of the bug
    reads_external_state=False,
    sanitizer_fields=None,         # free text: cannot declassify
)

try:
    annotate_memory_write(
        call=summarizer,
        input_provenance=fetched,
        store_has_tainted_rows=False,
        requested_taint=Taint.CLEAN,
    )
except TaintLaunderingError as e:
    print(f"quarantined: {e}")
