# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-promote-episodic-traces-into-semantic-memory-the-decay-crossing-contamination-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-promote-episodic-traces-into-semantic-memory-the-decay-crossing-contamination-invariant.warrant.json
# Markdown SHA-256:   e2972db1e14a014af0ac2353ee6464a69ef723ee16241202b137e748ac6fdeda
# Code AST SHA-256:   eeb2824d55120ae2a3888c9afcebe44a92269a1d1f0fcc876c0a4f9c0e0a25d0
# Verified Classes:   PredicateClass, EpisodicTrace, PromotionContaminationError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Dict, List, Optional


class PredicateClass(Enum):
    STATIONARY = "stationary"
    MUTABLE = "mutable"


@dataclass(frozen=True)
class EpisodicTrace:
    trace_id: str
    predicate_key: str
    value: str
    timestamp: int
    score: float  # decay-weighted retrieval score


class PromotionContaminationError(RuntimeError):
    """Raised when a distillation gate would promote a stale fact."""


def promote(
    fact: EpisodicTrace,
    log: List[EpisodicTrace],
    pred_class: PredicateClass,
    tau: float,
) -> Optional[EpisodicTrace]:
    key = fact.predicate_key
    peers = [t for t in log if t.predicate_key == key]

    if pred_class is PredicateClass.STATIONARY:
        # Score-gating is admissible: truth does not change under us.
        aggregate = sum(t.score for t in peers if t.value == fact.value)
        return fact if aggregate > tau else None

    # MUTABLE: gate on temporal ordering, never on aggregate score.
    latest = max(peers, key=lambda t: t.timestamp)
    if latest.trace_id != fact.trace_id:
        raise PromotionContaminationError(
            f"refusing to promote {fact.trace_id} ({key}={fact.value}): "
            f"superseded by {latest.trace_id} at t={latest.timestamp} "
            f"({key}={latest.value}); aggregate score {sum(t.score for t in peers)} "
            f"is not a truth signal for a mutable predicate"
        )
    return fact


def evict_episodic(
    log: List[EpisodicTrace],
    semantic_live: Dict[str, str],
    decay_threshold: float,
) -> List[EpisodicTrace]:
    """Evict low-score traces, but pin any event that contradicts a live semantic fact."""
    survivors = []
    for t in log:
        contradicts_live = (
            t.predicate_key in semantic_live
            and semantic_live[t.predicate_key] != t.value
        )
        if t.score < decay_threshold and not contradicts_live:
            continue
        survivors.append(t)
    return survivors
