# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-self-rewriting-context-policy-from-laundering-a-poisoned-instruction-into-a-trusted-summary-slot.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-self-rewriting-context-policy-from-laundering-a-poisoned-instruction-into-a-trusted-summary-slot.warrant.json
# Markdown SHA-256:   d552080f962ab3ea2ae2ec1c1c51f0ee3cf3ea95147a5f1019e88b50a35d5d09
# Code AST SHA-256:   f44189af557499eda3b6d4ee18ffb7d1001ebed0fd0e9de3248cbd8f4ef56c5a
# Verified Classes:   Tier, ProvenanceLaunderingError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import IntEnum


class Tier(IntEnum):
    # Higher = more trusted. Promotion means moving to a higher value.
    TOOL = 0
    PEER = 1
    USER = 2
    SYSTEM = 3


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a compaction pass would raise a span's trust tier."""


@dataclass(frozen=True)
class Span:
    span_id: str
    tier: Tier
    text: str


def compact(spans: list[Span], budget: int, salience: dict[str, float]) -> list[Span]:
    """Retain high-salience spans within budget, then verify tier preservation.

    Salience decides *what to keep*, never *what to trust*.
    """
    kept = sorted(spans, key=lambda s: salience.get(s.span_id, 0.0), reverse=True)
    out: list[Span] = []
    used = 0
    for s in kept:
        cost = len(s.text)
        if used + cost > budget:
            continue
        out.append(s)
        used += cost

    # Invariant: no span may appear at a higher tier than it entered with.
    before = {s.span_id: s.tier for s in spans}
    for s in out:
        if s.tier > before[s.span_id]:
            raise ProvenanceLaunderingError(
                f"span {s.span_id!r} promoted {before[s.span_id].name}->{s.tier.name} "
                f"during compaction; tier promotion requires an explicit voucher"
            )
    return out


def summarize(spans: list[Span], summary_id: str, text: str) -> Span:
    """A summary inherits the *least* trusted tier among its inputs."""
    if not spans:
        raise ProvenanceLaunderingError("cannot summarize an empty span set")
    least = min(s.tier for s in spans)
    return Span(span_id=summary_id, tier=least, text=text)
