# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-re-summarization-from-laundering-a-poisoned-memory-into-a-trusted-one.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-re-summarization-from-laundering-a-poisoned-memory-into-a-trusted-one.warrant.json
# Markdown SHA-256:   7690745242881c44d98ef958ce5e4dde23fd99ef86a168c5c28c82fb38d96016
# Code AST SHA-256:   cf36ded1cd0c2ed6a79842fd3fea9bac7f98429b9bb20cffee4cfab050a25e8c
# Verified Classes:   TrustTier, SummaryLaunderingError, Span, Summary
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import IntEnum
from typing import Sequence


class TrustTier(IntEnum):
    UNTRUSTED = 0      # tool output, retrieved web, user docs
    UNTRUSTED_DERIVED = 1  # summary of untrusted spans
    MODEL_REASONING = 2    # first-party inference, still fallible
    VERIFIED = 3       # re-checked against ground truth


class SummaryLaunderingError(RuntimeError):
    """Raised when a re-summarization would promote trust or drop a qualifier."""


QUALIFIERS = {"likely", "unverified", "per source", "disputed", "alleged"}


@dataclass(frozen=True)
class Span:
    span_id: str
    text: str
    trust: TrustTier


@dataclass(frozen=True)
class Summary:
    derived_from: tuple[str, ...]
    text: str
    min_trust: TrustTier


def compact(spans: Sequence[Span], summary_text: str,
            retained_propositions: dict[str, str]) -> Summary:
    """Re-summarize spans, enforcing the provenance invariant.

    retained_propositions maps a proposition -> the qualifier that guarded it
    in the source (empty string if unguarded).
    """
    if not spans:
        raise SummaryLaunderingError("cannot summarize an empty span set")

    # Invariant 1: trust is the minimum of inputs, never promoted.
    min_trust = min(s.trust for s in spans)

    # Invariant 2: no qualifier may be dropped from a retained proposition.
    source_text = " ".join(s.text.lower() for s in spans)
    for prop, qualifier in retained_propositions.items():
        if qualifier and qualifier.lower() in source_text:
            if qualifier.lower() not in summary_text.lower():
                raise SummaryLaunderingError(
                    f"qualifier '{qualifier}' dropped from retained "
                    f"proposition '{prop}' — modality shift is a laundering event"
                )

    # Invariant 3: a summary of untrusted spans may never authorize commitment.
    if min_trust <= TrustTier.UNTRUSTED_DERIVED:
        lowered = summary_text.lower()
        for imperative in ("deploy", "delete", "transfer", "commit"):
            if imperative in lowered:
                raise SummaryLaunderingError(
                    f"UNTRUSTED-DERIVED summary contains commitment "
                    f"verb '{imperative}'; must not be actionable"
                )

    return Summary(
        derived_from=tuple(s.span_id for s in spans),
        text=summary_text,
        min_trust=min_trust,
    )


def authorize_action(summary: Summary, action_class: str) -> None:
    """Gate: commitment-class actions require VERIFIED lineage."""
    if action_class == "commitment" and summary.min_trust < TrustTier.VERIFIED:
        raise SummaryLaunderingError(
            f"commitment action blocked: summary min_trust="
            f"{summary.min_trust.name}, requires VERIFIED; re-derive from "
            f"spans {summary.derived_from} before acting"
        )
