# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-propagation-through-semantic-memory-tiers-and-why-per-episode-provenance-tags-silently-fail.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-propagation-through-semantic-memory-tiers-and-why-per-episode-provenance-tags-silently-fail.warrant.json
# Markdown SHA-256:   05b2aa24f2e332360993ff44cde2a638714e3adb1b28b7b4874fc88e72a8eb43
# Code AST SHA-256:   23ee6212407fa9c8bebdd35addee23681251b8ba190ffaa05d0b61a1f7a1152b
# Verified Classes:   Taint, TaintLaunderingError, Episode, SemanticWrite, TaintStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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

class Taint(str, Enum):
    NONE = "none"
    USER = "user_statement"
    TOOL = "tool_output"
    INJECTION = "injection"

# Lattice join: set-union semantics; NONE is bottom.
def join(taints: Iterable[Taint]) -> frozenset[Taint]:
    result = frozenset(t for t in taints if t is not Taint.NONE)
    return result if result else frozenset({Taint.NONE})

def leq(a: frozenset[Taint], b: frozenset[Taint]) -> bool:
    """a ⊑ b : a is no more tainted than b."""
    return a <= b

class TaintLaunderingError(RuntimeError):
    """Raised when a semantic write claims less taint than the join of its derivation set."""
    def __init__(self, fact_id: str, claimed: frozenset[Taint], required: frozenset[Taint], edges: list[str]):
        self.fact_id = fact_id
        self.claimed = claimed
        self.required = required
        self.edges = edges
        super().__init__(
            f"fact {fact_id} claims taint {sorted(t.value for t in claimed)} "
            f"but derivation set {edges} requires {sorted(t.value for t in required)}"
        )

@dataclass
class Episode:
    turn_id: str
    taint: frozenset[Taint]

@dataclass
class SemanticWrite:
    fact_id: str
    derived_from: list[str]
    claimed_taint: frozenset[Taint]

class TaintStore:
    def __init__(self) -> None:
        self.episodes: dict[str, Episode] = {}
        self.facts: dict[str, SemanticWrite] = {}

    def add_episode(self, ep: Episode) -> None:
        self.episodes[ep.turn_id] = ep

    def write_semantic(self, w: SemanticWrite) -> frozenset[Taint]:
        missing = [tid for tid in w.derived_from if tid not in self.episodes]
        if missing:
            # Cannot compute join over unknown inputs -> cannot certify clean.
            raise TaintLaunderingError(w.fact_id, w.claimed_taint, frozenset({Taint.INJECTION}), missing)

        required = join(self.episodes[tid].taint for tid in w.derived_from)
        if not leq(w.claimed_taint, required):
            # Writer claims LESS taint than its inputs require: monotonicity violation.
            raise TaintLaunderingError(w.fact_id, w.claimed_taint, required, w.derived_from)

        stamped = SemanticWrite(w.fact_id, w.derived_from, required)
        self.facts[w.fact_id] = stamped
        return required
