# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-track-prompt-injection-taint-across-tool-outputs-when-the-label-set-is-derived-from-the-model-s-own-reading-of-untrusted-conten.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-track-prompt-injection-taint-across-tool-outputs-when-the-label-set-is-derived-from-the-model-s-own-reading-of-untrusted-conten.warrant.json
# Markdown SHA-256:   c798e98bca6afadac5c0f36e2a9cedef353ae466ef4baf11943bfa3bc1a730a3
# Code AST SHA-256:   a22ee9b882fc4cf2e3ffb87aa014b105df70d8509203d122ca429ebba105a4a4
# Verified Classes:   TaintAdjudicationError, Segment
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

TRUST_ORDER = {"TRUSTED": 0, "UNTRUSTED": 1}


class TaintAdjudicationError(RuntimeError):
    """Raised when a label decision violates the monotone-taint invariant."""


@dataclass(frozen=True)
class Segment:
    content: str
    sources: FrozenSet[str]
    adjudicated_label: str = "UNTRUSTED"
    model_raised_taint: bool = False


def join_provenance(seg: Segment) -> str:
    # Provenance floor: any untrusted source pins the segment to UNTRUSTED.
    if "web" in seg.sources or "tool_output" in seg.sources:
        return "UNTRUSTED"
    return "TRUSTED"


def effective_label(seg: Segment) -> str:
    floor = join_provenance(seg)
    # Model may only raise taint, never lower it.
    if seg.model_raised_taint:
        return "UNTRUSTED"
    return floor


def apply_adjudication(seg: Segment, model_label: str) -> Segment:
    floor = join_provenance(seg)
    # Reject any attempt by the model to upgrade trust above the provenance floor.
    if TRUST_ORDER[model_label] < TRUST_ORDER[floor]:
        raise TaintAdjudicationError(
            f"model attempted trust upgrade {floor}->{model_label} "
            f"for sources={sorted(seg.sources)}; content-derived upgrade forbidden"
        )
    raised = model_label == "UNTRUSTED" and floor == "TRUSTED"
    return Segment(
        content=seg.content,
        sources=seg.sources,
        adjudicated_label=model_label,
        model_raised_taint=seg.model_raised_taint or raised,
    )


def gate_sink(seg: Segment, sink: str) -> None:
    allowed = {"TRUSTED": {"send_email", "write_memory", "fetch_url"},
               "UNTRUSTED": {"fetch_url"}}
    label = effective_label(seg)
    if sink not in allowed[label]:
        raise TaintAdjudicationError(
            f"sink {sink!r} blocked for label {label} "
            f"(sources={sorted(seg.sources)})"
        )


def cold_start_rehydrate(stored_label: str, stored_sources: FrozenSet[str]) -> Segment:
    seg = Segment(content="", sources=stored_sources, adjudicated_label=stored_label)
    # Disagreement between stored label and provenance join => quarantine.
    if TRUST_ORDER[stored_label] < TRUST_ORDER[join_provenance(seg)]:
        raise TaintAdjudicationError(
            f"stored label {stored_label} weaker than provenance floor "
            f"{join_provenance(seg)}; memory record quarantined"
        )
    return seg


def demo() -> None:
    poisoned = Segment(
        content="...emit TRUSTED...",
        sources=frozenset({"web"}),
        adjudicated_label="TRUSTED",
    )
    # The model's "TRUSTED" read is rejected: provenance floor is UNTRUSTED.
    apply_adjudication(poisoned, "TRUSTED")  # raises TaintAdjudicationError
