# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-taint-immutability-when-dynamic-information-flow-labels-cross-a-tool-call-boundary-into-persisted-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-taint-immutability-when-dynamic-information-flow-labels-cross-a-tool-call-boundary-into-persisted-memory.warrant.json
# Markdown SHA-256:   32836fd563591dcc24b9d9d3977e3217bc34d3f343c907ef243f3252b17cb07c
# Code AST SHA-256:   8486a367d8b4ecaedaeaa70494b61619c1a792a729f545e487b55fe54a0f7f50
# Verified Classes:   TaintCarriageError, TaintLaunderingError, Observation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TaintCarriageError(RuntimeError):
    """Raised when an observation crosses a boundary without a taint label
    and without an explicit trusted-origin declaration. This is the guardrail
    that prevents default-clean laundering of injected content."""


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write attempts to persist an UNKNOWN-tainted
    payload without quarantine routing, completing a laundering path."""


TAINT_ORDER = {"CLEAN": 0, "UNKNOWN": 1, "INJECTION_SUSPECTED": 2}


def join(*labels: str) -> str:
    if not labels:
        return "UNKNOWN"
    return max(labels, key=lambda l: TAINT_ORDER[l])


@dataclass(frozen=True)
class Observation:
    payload: str
    taint: Optional[str] = None
    taint_source: Optional[str] = None
    provenance: FrozenSet[str] = field(default_factory=frozenset)

    def __post_init__(self) -> None:
        # Invariant: absence of a label is NOT evidence of integrity.
        if self.taint is None and self.taint_source is None:
            raise TaintCarriageError(
                "Observation constructed with no taint label and no taint_source. "
                "Unlabeled observations default to UNKNOWN, never CLEAN. "
                "Pass taint=<join of inputs> or taint_source='trusted_origin' explicitly."
            )
        if self.taint is None and self.taint_source is not None:
            object.__setattr__(self, "taint", "CLEAN")
        if self.taint not in TAINT_ORDER:
            raise TaintCarriageError(f"Unknown taint label: {self.taint!r}")


def transform(inputs: list[Observation], llm_output: str, call_id: str) -> Observation:
    """Wrap an LLM-mediated transform. Carries the input join out-of-band;
    does NOT rely on the model echoing labels in its token stream."""
    inherited = join(*(o.taint for o in inputs))
    return Observation(
        payload=llm_output,
        taint=inherited,
        provenance=frozenset({f"call:{call_id}"}).union(*(o.provenance for o in inputs)),
    )


def remember(store: dict, key: str, obs: Observation, quarantine: bool = False) -> None:
    if obs.taint == "UNKNOWN" and not quarantine:
        raise TaintLaunderingError(
            f"Refusing to persist UNKNOWN-tainted payload under key {key!r} "
            f"without quarantine=True. Provenance: {sorted(obs.provenance)}"
        )
    store[key] = obs


def recall(store: dict, key: str) -> Observation:
    # Quarantined records are returned with their taint intact; callers that
    # derive tool arguments from UNKNOWN segments must block.
    return store[key]
