# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-conflates-decayed-episodic-traces-with-semantic-memory-during-embedding-indexed-retrieval.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-conflates-decayed-episodic-traces-with-semantic-memory-during-embedding-indexed-retrieval.warrant.json
# Markdown SHA-256:   4baa1866b53d9d3760ccbb8b0a47e02e04765632fd8c286a6c80166991d40484
# Code AST SHA-256:   67a4bc4ded3cb6354fcc3896fbf880fffadfb69691948b33e1b2378ccb12856a
# Verified Classes:   DecayedTracePromotionError, MemoryEntry
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass
from typing import Literal

DECAY_FLOOR = 0.10          # episodic entries below this are categorically inadmissible
EPISODIC_QUOTA = 2          # max episodic snippets injected per retrieval
SEMANTIC_QUOTA = 5


class DecayedTracePromotionError(RuntimeError):
    """Raised when a decayed episodic trace would be admitted to the reasoning context."""


@dataclass
class MemoryEntry:
    text: str
    source: Literal["episodic", "semantic"]
    embedding_sim: float          # cosine similarity to query, in [0, 1]
    decay_weight: float = 1.0     # episodic only; monotone non-increasing with age
    confidence: float = 1.0       # semantic only
    as_of: str = ""


def gate_and_rank(query_sim_floor: float, entries: list[MemoryEntry]) -> list[MemoryEntry]:
    # Stage 1: categorical hard filter on decay BEFORE any ranking.
    admissible: list[MemoryEntry] = []
    for e in entries:
        if e.source == "episodic":
            if e.decay_weight < DECAY_FLOOR:
                # Categorically inadmissible: similarity must not resurrect it.
                if e.embedding_sim >= query_sim_floor:
                    raise DecayedTracePromotionError(
                        f"episodic trace below decay floor "
                        f"(w={e.decay_weight:.3f} < {DECAY_FLOOR}) "
                        f"matched query at sim={e.embedding_sim:.3f}; "
                        f"refusing promotion to reasoning context: {e.text!r}"
                    )
                continue
            e_score = e.embedding_sim * e.decay_weight
        else:
            e_score = e.embedding_sim * e.confidence
        admissible.append((e_score, e))

    # Stage 2: rank within store, enforce provenance quota, tag provenance.
    admissible.sort(key=lambda t: t[0], reverse=True)
    episodic = [e for s, e in admissible if e.source == "episodic"][:EPISODIC_QUOTA]
    semantic = [e for s, e in admissible if e.source == "semantic"][:SEMANTIC_QUOTA]
    return semantic + episodic


def retrieve(query_sim_floor: float, entries: list[MemoryEntry]) -> list[str]:
    ranked = gate_and_rank(query_sim_floor, entries)
    return [
        f"[{e.source} as_of={e.as_of} "
        f"{'w=' + format(e.decay_weight, '.2f') if e.source == 'episodic' else 'conf=' + format(e.confidence, '.2f')}] "
        f"{e.text}"
        for e in ranked
    ]
