# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-context-windows-from-laundering-a-poisoned-memory-slot.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-context-windows-from-laundering-a-poisoned-memory-slot.warrant.json
# Markdown SHA-256:   597031281ed44bce796be10b1c965c68877bef2884e51f88369d6884f6bb7a9b
# Code AST SHA-256:   8ad740a3014033095b43587637cc239350eed41aab0fbbc0e5038e327a0857d3
# Verified Classes:   ContextLaunderingError, Entry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

TAU = 0.7  # salience threshold above which an entry is treated as active evidence


class ContextLaunderingError(RuntimeError):
    """Raised when a self-edit promotes a tainted/superseded entry into the active set
    without propagating its contradiction closure or re-verifying it."""


@dataclass
class Entry:
    id: str
    content: str
    salience: float
    verification_status: str  # "verified" | "unverified" | "superseded"
    superseded_by: Optional[str] = None
    contradicts: set = field(default_factory=set)


def apply_promotion(buffer: dict, entry_id: str, new_salience: float) -> None:
    """Harness-side guard for a model-issued PROMOTE op on a self-editing buffer."""
    entry = buffer[entry_id]

    # Invariant 1: superseded entries may never be promoted into the active set.
    if entry.superseded_by is not None:
        raise ContextLaunderingError(
            f"promotion of superseded entry {entry_id!r} (superseded_by={entry.superseded_by!r}) "
            f"would launder a stale claim; require REQUEST_REVERIFY instead"
        )

    # Invariant 2: promoting one side of a contradiction must promote the whole closure.
    if new_salience > TAU and entry.contradicts:
        unpropagated = [
            other for other in entry.contradicts
            if buffer[other].salience <= TAU
        ]
        if unpropagated:
            raise ContextLaunderingError(
                f"promotion of {entry_id!r} to {new_salience} leaves contradiction "
                f"closure {unpropagated!r} below tau={TAU}; promote the pair or block"
            )

    # Invariant 3: unverified entries above tau require an explicit re-verify op.
    if new_salience > TAU and entry.verification_status == "unverified":
        raise ContextLaunderingError(
            f"promotion of unverified entry {entry_id!r} to {new_salience} requires "
            f"REQUEST_REVERIFY before it may enter the active evidence set"
        )

    entry.salience = new_salience
