# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-result-provenance-as-a-per-turn-taint-label-rather-than-a-per-session-trust-bit.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-result-provenance-as-a-per-turn-taint-label-rather-than-a-per-session-trust-bit.warrant.json
# Markdown SHA-256:   2156bc96e76c0586f7bd324a971765544a5f5feca6bb602f198cd8fef85a1e0b
# Code AST SHA-256:   77ecb37373fceef6b65605833f64ee996812f6a7b7e3b32e64edc29f07b374ef
# Verified Classes:   Taint, TaintLaunderingError, Fact, TaintTracker
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class Taint(IntEnum):
    UNTRUSTED = 0
    TRUSTED = 1


class TaintLaunderingError(RuntimeError):
    """Raised when a fact would be acted upon at a taint higher than its derivation chain permits."""


@dataclass
class Fact:
    predicate: str
    value: str
    taint: Taint
    source: str  # e.g. "fetch_url(vendorB/sla)@turn6"
    derivation: tuple[str, ...] = field(default_factory=tuple)


class TaintTracker:
    def __init__(self) -> None:
        self._facts: dict[str, Fact] = {}

    def store(self, fact: Fact) -> None:
        # Fail-closed: a fact with no source annotation is untrusted regardless of claimed taint.
        if not fact.source:
            fact = Fact(fact.predicate, fact.value, Taint.UNTRUSTED, source="<unknown>")
        existing = self._facts.get(fact.predicate)
        if existing is not None and existing.value != fact.value:
            # Contradiction: taint-first, recency never wins across differing taint.
            if fact.taint < existing.taint:
                # new untrusted claim contradicts trusted fact -> quarantine new, keep old
                return
            if fact.taint > existing.taint:
                # new trusted fact supersedes untrusted -> allowed
                self._facts[fact.predicate] = fact
                return
            # equal taint, differing value: cannot resolve silently
            raise TaintLaunderingError(
                f"unresolved contradiction on {fact.predicate!r} at equal taint "
                f"({existing.value!r} vs {fact.value!r})"
            )
        self._facts[fact.predicate] = fact

    def act(self, predicate: str, require: Taint = Taint.TRUSTED) -> Fact:
        fact = self._facts.get(predicate)
        if fact is None:
            raise TaintLaunderingError(f"no fact for {predicate!r}")
        if fact.taint < require:
            raise TaintLaunderingError(
                f"cannot act on {predicate!r}: taint={fact.taint.name} "
                f"< required={require.name}, source={fact.source}"
            )
        return fact

    def compact(self, predicates: list[str]) -> Fact:
        # Summary taint is the min over inputs; it cannot launder upward.
        members = [self._facts[p] for p in predicates if p in self._facts]
        if not members:
            raise TaintLaunderingError("cannot compact empty fact set")
        min_taint = min(m.taint for m in members)
        return Fact(
            predicate="summary",
            value=";".join(f"{m.predicate}={m.value}" for m in members),
            taint=min_taint,
            source="compact(" + ",".join(m.source for m in members) + ")",
            derivation=tuple(m.source for m in members),
        )


def demo() -> None:
    t = TaintTracker()
    # Turn 2: trusted distillation from clean fetch.
    t.store(Fact("A.sla_uptime", "99.9%", Taint.TRUSTED, "fetch_url(vendorA/sla)@turn1"))
    # Turn 6: attacker-modified page, must be labeled untrusted.
    t.store(Fact("A.sla_uptime", "99.5%", Taint.UNTRUSTED, "fetch_url(vendorB/sla)@turn6"))
    # Turn 7: acting on the SLA fact must use the trusted value.
    fact = t.act("A.sla_uptime")
    assert fact.value == "99.9%", fact

    # Attempting to act on a fact whose only source is untrusted must raise.
    t.store(Fact("B.sla_uptime", "99.0%", Taint.UNTRUSTED, "fetch_url(vendorB/sla)@turn6"))
    try:
        t.act("B.sla_uptime")
    except TaintLaunderingError as e:
        print("blocked:", e)
    else:
        raise TaintLaunderingError("guardrail failed: untrusted fact was acted upon as trusted")


if __name__ == "__main__":
    demo()
