# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-memory-write-before-it-crosses-a-trust-region-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-memory-write-before-it-crosses-a-trust-region-boundary.warrant.json
# Markdown SHA-256:   2ae6362075df15701250aa44acef2d9f28a2357ea8a8cb2492e2f8fc85d4bb1e
# Code AST SHA-256:   ec3dd6fc357dac6a21cb2d93f4fd15fb1dbd02e353fb6f24f9949cfcfbc64776
# Verified Classes:   Provenance, TaintLaunderingError, DerivedMemory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass
from enum import Enum


class Provenance(Enum):
    TRUSTED = "trusted"
    UNVERIFIED = "unverified"
    UNTRUSTED = "untrusted"


# Join-semilattice: trusted < unverified < untrusted in taint severity.
_ORDER = {Provenance.TRUSTED: 0, Provenance.UNVERIFIED: 1, Provenance.UNTRUSTED: 2}


def join(a: Provenance, b: Provenance) -> Provenance:
    return a if _ORDER[a] >= _ORDER[b] else b


class TaintLaunderingError(RuntimeError):
    """Raised when a derived memory write would strip taint from its inputs."""


@dataclass(frozen=True)
class DerivedMemory:
    text: str
    provenance: Provenance
    derivation_hash: str | None


def write_semantic_memory(
    text: str,
    input_provenances: list[Provenance],
    derivation_hash: str | None,
    pinned_prompt_hash: str | None,
) -> DerivedMemory:
    if not input_provenances:
        raise TaintLaunderingError("no input provenance recorded; cannot derive label")

    effective = Provenance.TRUSTED
    for p in input_provenances:
        effective = join(effective, p)

    # The caller's principal is deliberately NOT consulted here.
    if effective == Provenance.TRUSTED:
        if derivation_hash is None or derivation_hash != pinned_prompt_hash:
            raise TaintLaunderingError(
                f"trusted-labeled write with unverifiable derivation "
                f"(hash={derivation_hash!r}, pinned={pinned_prompt_hash!r})"
            )
        return DerivedMemory(text, Provenance.TRUSTED, derivation_hash)

    # Tainted or unverifiable inputs: refuse to promote into trusted region.
    # Caller must route to quarantine; promotion here is laundering.
    raise TaintLaunderingError(
        f"join of input provenances = {effective.value}; "
        f"refusing trusted write, route to quarantine tier"
    )


def retrieve_into_trusted_region(entry: DerivedMemory) -> DerivedMemory:
    if entry.provenance != Provenance.TRUSTED:
        raise TaintLaunderingError(
            f"retrieval of {entry.provenance.value} memory into trusted region refused"
        )
    return entry
