# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-provenance-tainted-memory-writes-before-semantic-distillation-and-why-taint-decay-across-tool-call-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-provenance-tainted-memory-writes-before-semantic-distillation-and-why-taint-decay-across-tool-call-chain.warrant.json
# Markdown SHA-256:   62069246828bd85a1d6114a2a37c6d09d799b6f23df26d5634f413cadcecd488
# Code AST SHA-256:   607524cf25fd28abbfc703365d4d2e23464c15c0cb377326b6082937888d2f32
# Verified Classes:   Taint, TaintLaunderingError, Provenance
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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

class Taint(IntEnum):
    NONE = 0
    LOW = 1
    MEDIUM = 2
    HIGH = 3

class TaintLaunderingError(RuntimeError):
    """Raised when a tool boundary or distillation step attempts to clear
    taint without an accountable declassification event."""
    pass

@dataclass
class Provenance:
    source: str
    taint: Taint
    lineage: tuple = field(default_factory=tuple)

def propagate_through_tool(inp: Provenance, tool_name: str,
                           tool_declassifies: bool,
                           output_text: str) -> Provenance:
    # A trusted executor is not a sanitizer. Taint is monotonic unless the
    # tool schema explicitly declares declassification capability.
    if not tool_declassifies and inp.taint >= Taint.MEDIUM:
        return Provenance(
            source=f"tool:{tool_name}",
            taint=inp.taint,  # inherited, NOT reset
            lineage=inp.lineage + (f"tool:{tool_name}",),
        )
    if tool_declassifies:
        # Declassification must be recorded; here we require the caller to
        # have already attached a principal, else refuse.
        raise TaintLaunderingError(
            f"tool {tool_name} claims declassification but no principal "
            f"attached to lineage {inp.lineage}"
        )
    return Provenance(source=f"tool:{tool_name}", taint=inp.taint,
                      lineage=inp.lineage + (f"tool:{tool_name}",))

def write_memory(prov: Provenance, key: str, value: str,
                 persistent: bool = True) -> dict:
    if persistent and prov.taint >= Taint.MEDIUM:
        # Quarantine: do not enter the semantic store's trusted tier.
        return {"key": key, "value": value, "quarantined": True,
                "taint": prov.taint, "lineage": prov.lineage}
    return {"key": key, "value": value, "quarantined": False,
            "taint": prov.taint, "lineage": prov.lineage}

def distill_to_semantic(record: dict) -> dict:
    if record["quarantined"] or record["taint"] >= Taint.MEDIUM:
        raise TaintLaunderingError(
            f"refusing to promote tainted record {record['key']} "
            f"(taint={record['taint']}, lineage={record['lineage']}); "
            f"declassify with an accountable principal first"
        )
    return {"key": record["key"], "value": record["value"],
            "taint": Taint.NONE}
