# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-tainted-provenance-label-survives-a-memory-write-but-not-the-retrieval-that-later-reads-it.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-tainted-provenance-label-survives-a-memory-write-but-not-the-retrieval-that-later-reads-it.warrant.json
# Markdown SHA-256:   7836ae8c77bd08158c7e16f3bebef3292a29f1282f3ab53698d539813a58aadb
# Code AST SHA-256:   1977a2291a0a29e543893bf38545125584426ada5242808177116a73f659296c
# Verified Classes:   TaintProjectionError, Fragment, ProjectedChunk
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintProjectionError(RuntimeError):
    """Raised when a memory projection drops or downgrades a provenance label."""
    pass


@dataclass
class Fragment:
    text: str
    source: str
    provenance: str  # e.g. "trusted:user", "untrusted:web"


@dataclass
class ProjectedChunk:
    text: str
    source: str
    score: float
    provenance: Optional[str] = None  # must be populated by every read path


TRUST_RANK = {"trusted:user": 2, "trusted:system": 2, "untrusted:web": 0, "untrusted:tool": 0}


def max_taint(fragments: list[Fragment]) -> str:
    if not fragments:
        return "trusted:system"
    return min(fragments, key=lambda f: TRUST_RANK.get(f.provenance, 0)).provenance


def project(fragments: list[Fragment]) -> list[ProjectedChunk]:
    """Read path. MUST project provenance; omitting it is the failure mode."""
    out = []
    for f in fragments:
        chunk = ProjectedChunk(text=f.text, source=f.source, score=0.9, provenance=f.provenance)
        if chunk.provenance is None:
            raise TaintProjectionError(
                f"projection dropped provenance for source={f.source!r}; "
                "taint would be invisible at decision point"
            )
        out.append(chunk)
    return out


def enforce_decision_boundary(chunks: list[ProjectedChunk], required_trust: str, action: str) -> None:
    """Policy gate. Keys on assembled-context taint, not on triggering-turn provenance."""
    for c in chunks:
        if c.provenance is None:
            raise TaintProjectionError(
                f"chunk from {c.source!r} reached decision point without provenance; "
                "cannot evaluate trust for action {action!r}"
            )
    assembled = min(chunks, key=lambda c: TRUST_RANK.get(c.provenance or "", 0)).provenance
    if TRUST_RANK.get(assembled or "", 0) < TRUST_RANK[required_trust]:
        raise TaintProjectionError(
            f"action {action!r} requires {required_trust!r} but assembled context is {assembled!r}"
        )


def distill(inputs: list[Fragment], summary_text: str) -> Fragment:
    """Episodic -> semantic. Output taint must be max over inputs (no laundering)."""
    inherited = max_taint(inputs)
    out = Fragment(text=summary_text, source="distilled", provenance=inherited)
    if TRUST_RANK.get(out.provenance, 0) > min(TRUST_RANK.get(f.provenance, 0) for f in inputs):
        raise TaintProjectionError("distillation lowered taint below input maximum (laundering)")
    return out
