# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-consolidation-poisoning-from-a-stale-episodic-replay-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-consolidation-poisoning-from-a-stale-episodic-replay-window.warrant.json
# Markdown SHA-256:   17ca5c646469dc38ac14607aec45dc7cabbb7591f2c49ef47119d5378009cd5b
# Code AST SHA-256:   e023fcd726768a9b1020c39a782d6ed154d7bb3bd91ade59c74f8c09708fee5e
# Verified Classes:   ConsolidationPoisoningError, SemanticFact, ContradictionEntry
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass

PROBE_CONFIDENCE_THRESHOLD = 0.8
NEGATIVE_DECAY_HALFLIFE_S = 7 * 24 * 3600  # one week


class ConsolidationPoisoningError(RuntimeError):
    """Raised when a consolidated fact is served above the confidence that
    its most recent contradicting (possibly abandoned) trace permits."""


@dataclass
class SemanticFact:
    subject: str
    value: str
    stored_confidence: float
    consolidated_at: float


@dataclass
class ContradictionEntry:
    subject: str
    last_negative_at: float


def decayed_cap(now: float, last_negative_at: float) -> float:
    age = max(0.0, now - last_negative_at)
    return 0.5 ** (age / NEGATIVE_DECAY_HALFLIFE_S)


def serve_fact(
    fact: SemanticFact,
    contradictions: dict[str, ContradictionEntry],
    now: float | None = None,
) -> tuple[str, float, bool]:
    """Return (value, served_confidence, requires_probe)."""
    now = time.time() if now is None else now
    served = fact.stored_confidence

    entry = contradictions.get(fact.subject)
    if entry is not None:
        cap = decayed_cap(now, entry.last_negative_at)
        served = min(served, cap)

    requires_probe = served < PROBE_CONFIDENCE_THRESHOLD

    # Invariant guard: a fact contradicted by a trace must never be served at a
    # confidence that would suppress the pre-flight probe.
    if entry is not None and served >= PROBE_CONFIDENCE_THRESHOLD:
        raise ConsolidationPoisoningError(
            f"fact '{fact.subject}' served at {served:.3f} (>= probe threshold "
            f"{PROBE_CONFIDENCE_THRESHOLD}) despite contradiction at "
            f"t={entry.last_negative_at:.0f}; consolidation poisoned the "
            f"confidence signal and would suppress verification."
        )

    return fact.value, served, requires_probe


def consolidate(
    fact: SemanticFact,
    contradictions: dict[str, ContradictionEntry],
    now: float | None = None,
) -> SemanticFact:
    """Fold contradiction evidence into stored confidence at distillation time."""
    now = time.time() if now is None else now
    entry = contradictions.get(fact.subject)
    if entry is not None:
        cap = decayed_cap(now, entry.last_negative_at)
        if cap < fact.stored_confidence:
            fact.stored_confidence = cap
    return fact
