# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-avoid-promoting-episodic-traces-into-semantic-memory-during-retrieval-augmented-consolidation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-avoid-promoting-episodic-traces-into-semantic-memory-during-retrieval-augmented-consolidation.warrant.json
# Markdown SHA-256:   a5deb84d33f7a31691452faba746136459ef55efbd8dddb12df498b544b53f18
# Code AST SHA-256:   fda47effdf775ab7d6fead1c99b7622c095eb0e5b548f199193e804977f89816
# Verified Classes:   PromotionInvariantError, EpisodicTrace, SemanticAssertion
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class PromotionInvariantError(RuntimeError):
    """Raised when an episodic trace is about to be promoted without satisfying
    the entailment / provenance / supersession invariant."""
    pass


@dataclass
class EpisodicTrace:
    trace_id: str
    text: str
    source: Optional[str]
    timestamp: float
    session: Optional[str]
    surfaced_by_query: Optional[str]
    retrieval_count: int
    self_caused_retrievals: int
    entity_overlap_ratio: float
    provenance_disjoint_corroborations: int


@dataclass
class SemanticAssertion:
    assertion_id: str
    text: str
    timestamp: float
    supersedes: Optional[str] = None


HUB_OVERLAP_CEILING = 0.55
PROMOTION_RETRIEVAL_THRESHOLD = 3


def _provenance_closed(t: EpisodicTrace) -> bool:
    return all([t.source, t.session, t.surfaced_by_query]) and t.timestamp > 0


def _independent_retrievals(t: EpisodicTrace) -> int:
    return max(0, t.retrieval_count - t.self_caused_retrievals)


def _is_hub_artifact(t: EpisodicTrace) -> bool:
    return t.entity_overlap_ratio > HUB_OVERLAP_CEILING


def _entails(t: EpisodicTrace, candidate: str) -> bool:
    # Placeholder for a real verifier; must reject mere entity adjacency.
    return candidate.strip().lower() in t.text.strip().lower()


def route_promotion(
    trace: EpisodicTrace,
    candidate: str,
    current_store: list[SemanticAssertion],
) -> str:
    if not _provenance_closed(trace):
        raise PromotionInvariantError(
            f"trace {trace.trace_id} has open provenance; quarantine, do not promote"
        )

    if _independent_retrievals(trace) < PROMOTION_RETRIEVAL_THRESHOLD:
        return "hold:insufficient_independent_retrieval"

    if _is_hub_artifact(trace) and trace.provenance_disjoint_corroborations < 1:
        raise PromotionInvariantError(
            f"trace {trace.trace_id} is a hub artifact "
            f"(overlap={trace.entity_overlap_ratio:.2f}) with no disjoint corroboration"
        )

    if not _entails(trace, candidate):
        raise PromotionInvariantError(
            f"trace {trace.trace_id} does not entail candidate assertion; "
            "similarity is not a promotion license"
        )

    for existing in current_store:
        if existing.text.strip().lower() == candidate.strip().lower():
            return "noop:already_present"
        if existing.supersedes == trace.trace_id:
            return "noop:already_superseded"

    conflicts = [
        a for a in current_store
        if a.text.strip().lower() != candidate.strip().lower()
        and _shares_entity(a.text, candidate)
    ]
    if conflicts:
        newest = max(conflicts, key=lambda a: a.timestamp)
        if trace.timestamp <= newest.timestamp and newest.supersedes != trace.trace_id:
            raise PromotionInvariantError(
                f"trace {trace.trace_id} conflicts with newer assertion "
                f"{newest.assertion_id} and has no supersession edge"
            )
        return f"resolve:supersede:{newest.assertion_id}"

    return "promote"


def _shares_entity(a: str, b: str) -> bool:
    return bool(set(a.lower().split()) & set(b.lower().split()))
