# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-episodic-to-semantic-promotion-from-poisoning-the-semantic-store-under-decay-aware-forgetting.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-episodic-to-semantic-promotion-from-poisoning-the-semantic-store-under-decay-aware-forgetting.warrant.json
# Markdown SHA-256:   4ab8322aea5efb8b32d61442a7d44c47e65d15de63922141cee2df67e8093da2
# Code AST SHA-256:   f87e6105a3f07d9d7dfc794f987e51dd7577de08429e7d73bbc3f3220b894593
# Verified Classes:   PromotionInvariantError, EpisodicRecord, PromotionConfig
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass, field
from typing import Literal


class PromotionInvariantError(RuntimeError):
    """Raised when an episodic cluster is promoted to semantic memory
    without satisfying the provenance-typed diversity gate."""
    pass


SourceClass = Literal["authoritative", "idempotent", "ambiguous", "unverified"]


@dataclass
class EpisodicRecord:
    record_id: str
    content: str
    source_fingerprint: str
    source_class: SourceClass
    created_at: float
    hits: int = 0
    distinct_confirmations: int = 1
    contradictions: int = 0


@dataclass
class PromotionConfig:
    decay_lambda: float = 0.05          # per hour
    alpha: float = 0.15                 # reinforcement weight
    theta_p: float = 1.0                # promotion threshold
    min_distinct_sources: int = 2       # k
    max_contradiction_rate: float = 0.1 # epsilon
    authoritative_sources: tuple = ("authoritative", "idempotent")


def salience(rec: EpisodicRecord, now: float, cfg: PromotionConfig) -> float:
    dt = max(0.0, now - rec.created_at)
    decay = math.exp(-cfg.decay_lambda * dt)
    # NOTE: reinforcement uses distinct_confirmations, NOT hits.
    reinforce = 1.0 + cfg.alpha * rec.distinct_confirmations
    return decay * reinforce


def contradiction_rate(rec: EpisodicRecord) -> float:
    total = rec.distinct_confirmations + rec.contradictions
    if total == 0:
        return 1.0
    return rec.contradictions / total


def try_promote(
    rec: EpisodicRecord,
    now: float,
    cfg: PromotionConfig,
) -> str | None:
    """Return the semantic fact string if promotion is valid, else None.
    Raises PromotionInvariantError if a caller attempts to bypass the gate
    for a non-authoritative single-source record above threshold."""
    score = salience(rec, now, cfg)

    if score < cfg.theta_p:
        return None  # below threshold: stay episodic, keep decaying

    # Authoritative/idempotent sources may promote on score alone.
    if rec.source_class in cfg.authoritative_sources:
        return rec.content

    # Non-authoritative: diversity gate is mandatory.
    if rec.distinct_confirmations < cfg.min_distinct_sources:
        raise PromotionInvariantError(
            f"record {rec.record_id} crossed theta_p={cfg.theta_p} "
            f"(score={score:.3f}) with only "
            f"{rec.distinct_confirmations} distinct source(s); "
            f"source_class={rec.source_class}. "
            f"Decay salience cannot manufacture epistemic commitment."
        )

    if contradiction_rate(rec) > cfg.max_contradiction_rate:
        # Do not promote; route to reconciliation instead.
        return None

    return rec.content


def promote_batch(
    records: list[EpisodicRecord],
    now: float,
    cfg: PromotionConfig,
) -> dict[str, str]:
    facts: dict[str, str] = {}
    for rec in records:
        try:
            fact = try_promote(rec, now, cfg)
        except PromotionInvariantError:
            # Quarantine: leave episodic, flag for audit, do not promote.
            continue
        if fact is not None:
            facts[rec.record_id] = fact
    return facts
