# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-label-laundering-through-agent-authored-memory-summaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-label-laundering-through-agent-authored-memory-summaries.warrant.json
# Markdown SHA-256:   a1fe5f8ab8424823d1839cef81cb7d14d813453dc6cea02e486e513e689fddae
# Code AST SHA-256:   76033e417cded92192f02d3622724b13f7738c4403f6f2176cd2ce53509de562
# Verified Classes:   LabelLaunderingError, Integrity, Span, MemoryArtifact
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from enum import IntEnum
from typing import FrozenSet


class LabelLaunderingError(RuntimeError):
    """Raised when a write path would assign an integrity level higher than
    the join of its derivation inputs (the laundering channel)."""


class Integrity(IntEnum):
    TAINT = 0      # untrusted: web, tool output, user-supplied
    TRUSTED = 1    # first-party, provenance-preserving, or corroborated


def join(a: Integrity, b: Integrity) -> Integrity:
    # Non-absorbing: the minimum wins. TRUSTED does NOT absorb TAINT.
    return Integrity(min(int(a), int(b)))


@dataclass(frozen=True)
class Span:
    span_id: str
    integrity: Integrity


@dataclass
class MemoryArtifact:
    text: str
    origin: str                       # "self" | "tool" | "user"
    derived_from: FrozenSet[str] = field(default_factory=frozenset)
    integrity: Integrity = Integrity.TAINT


def write_memory(
    text: str,
    origin: str,
    derived_from: FrozenSet[str],
    span_index: dict[str, Span],
    claimed_integrity: Integrity,
) -> MemoryArtifact:
    if not derived_from:
        # Model-authored content with no provenance: floor at TAINT.
        # It may NOT be promoted to TRUSTED on the strength of origin alone.
        if claimed_integrity > Integrity.TAINT:
            raise LabelLaunderingError(
                f"origin={origin!r} claims {claimed_integrity.name} with no "
                f"derivation spans; unlabeled derivation is the laundering channel"
            )
        return MemoryArtifact(text, origin, derived_from, Integrity.TAINT)

    missing = derived_from - span_index.keys()
    if missing:
        raise LabelLaunderingError(
            f"derivation references unknown spans {sorted(missing)}; "
            f"provenance DAG is incomplete and the join cannot be computed"
        )

    effective = Integrity.TRUSTED
    for sid in derived_from:
        effective = join(effective, span_index[sid].integrity)

    if claimed_integrity > effective:
        raise LabelLaunderingError(
            f"write claims {claimed_integrity.name} but derivation join is "
            f"{effective.name} over spans {sorted(derived_from)}; "
            f"refusing to launder taint through a self-authored summary"
        )

    return MemoryArtifact(text, origin, derived_from, effective)


def resummarize(prior: MemoryArtifact, new_spans: FrozenSet[str],
                span_index: dict[str, Span], text: str) -> MemoryArtifact:
    # Retry/refinement path: union prior derivation so taint is monotone
    # non-decreasing and cannot be scrubbed by iterative rewriting.
    combined = prior.derived_from | new_spans
    span_index = dict(span_index)
    span_index[f"prior::{id(prior)}"] = Span(f"prior::{id(prior)}", prior.integrity)
    return write_memory(
        text=text,
        origin="self",
        derived_from=combined | {f"prior::{id(prior)}"},
        span_index=span_index,
        claimed_integrity=Integrity.TRUSTED,  # the attempted promotion
    )
