# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-route-an-episodic-memory-to-semantic-consolidation-when-decay-and-consolidation-triggers-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-route-an-episodic-memory-to-semantic-consolidation-when-decay-and-consolidation-triggers-disagree.warrant.json
# Markdown SHA-256:   9c55111f9cb165ea7cefd7ecdcb3531b50a056b232f9068923b247b321b15938
# Code AST SHA-256:   f1ca58e2ca17d0e40b90f4f87a34cbf6af7097b49a118062d0d9cd91c418c917
# Verified Classes:   ConsolidationRaceError, EpisodicRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ConsolidationRaceError(RuntimeError):
    """Raised when consolidation evaluates against records that decay may evict mid-flight."""
    pass


@dataclass
class EpisodicRecord:
    entity: str
    relation: str
    value: str
    created_at: float
    access_count: int = 1
    pinned: bool = False

    def salience(self, now: float, half_life_days: float = 7.0) -> float:
        age_days = (now - self.created_at) / 86400.0
        return 0.5 ** (age_days / half_life_days)


EVICTION_FLOOR = 0.15
SUPPORT_REQUIRED = 3
PIN_EPSILON = 0.05


def evaluate_consolidation(
    cluster: list[EpisodicRecord],
    now: float,
    half_life_days: float = 7.0,
) -> Optional[str]:
    # Pin supporters that are near the eviction floor before counting.
    for rec in cluster:
        s = rec.salience(now, half_life_days)
        if s < EVICTION_FLOOR + PIN_EPSILON:
            rec.pinned = True

    survivors = [r for r in cluster if r.salience(now, half_life_days) >= EVICTION_FLOOR]

    if any(r.pinned for r in cluster) and len(survivors) < SUPPORT_REQUIRED:
        # Evidence is being evicted faster than it can be consolidated.
        for r in cluster:
            r.pinned = False
        raise ConsolidationRaceError(
            f"cluster {cluster[0].entity}.{cluster[0].relation}: "
            f"only {len(survivors)}/{SUPPORT_REQUIRED} supporters survive decay; "
            f"decay clock outran consolidation trigger"
        )

    if len(survivors) < SUPPORT_REQUIRED:
        return None

    # Require the support window to span at least one half-life (anti-burst).
    span_days = (max(r.created_at for r in survivors) - min(r.created_at for r in survivors)) / 86400.0
    if span_days < half_life_days:
        for r in cluster:
            r.pinned = False
        return None  # burst repetition, not stable fact

    values = [r.value for r in survivors]
    modal = max(set(values), key=values.count)
    for r in cluster:
        r.pinned = False
    return modal
