# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-prompt-injection-taint-from-surviving-a-memory-write-round-trip.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-prompt-injection-taint-from-surviving-a-memory-write-round-trip.warrant.json
# Markdown SHA-256:   cabf5a9236ceb024ffb79ee7d7dfb8610f2a84980e26db167aeb95448e7fe0ea
# Code AST SHA-256:   effe7717d64eae621117b51e35910925ed2dc4892e1ae99d2d15f199ffcd07d2
# Verified Classes:   TaintContractError, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Trust = Literal["trusted", "untrusted"]


class TaintContractError(RuntimeError):
    """Raised when a taint invariant is violated across a memory round-trip."""


@dataclass
class MemoryRecord:
    text: str
    trust: Trust | None          # None is a contract violation, never a default
    source: str
    derived_from: list[str] = field(default_factory=list)


def write_record(record: MemoryRecord, store: list[MemoryRecord]) -> None:
    # Invariant 1: label-carrying write. Missing trust fails closed at write time.
    if record.trust is None:
        raise TaintContractError(
            f"record from {record.source!r} has no trust label; refusing default-trust write"
        )
    store.append(record)


def build_embedding(record: MemoryRecord) -> str:
    # Invariant 2: projection must be label-inclusive, or the embedding is a
    # laundering channel that ranks tainted text without carrying its label.
    if record.trust == "untrusted":
        return f"[UNTRUSTED:{record.source}] {record.text}"
    return record.text


def rehydrate(record: MemoryRecord) -> dict:
    # Invariant 3: label-preserving re-hydration into a structurally distinct region.
    if record.trust == "untrusted":
        return {"region": "untrusted_evidence", "source": record.source, "text": record.text}
    if record.trust == "trusted":
        return {"region": "trusted_facts", "source": record.source, "text": record.text}
    raise TaintContractError("rehydrate received unlabeled record")


def authorize_action(
    call_args: dict[str, str],
    ancestry: dict[str, MemoryRecord],
) -> None:
    # Invariant 4: gate on provenance reachability, not on prose salience.
    for arg_name, value in call_args.items():
        for record_id, record in ancestry.items():
            if value in record.text and record.trust == "untrusted":
                raise TaintContractError(
                    f"action argument {arg_name!r} derives from untrusted record "
                    f"{record_id!r} (source={record.source!r}); "
                    f"escalate to verification instead of acting"
                )
