# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-procedural-store-promotion-when-semantic-retrieval-confidence-is-structurally-inflated-by-episodic-recency.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-procedural-store-promotion-when-semantic-retrieval-confidence-is-structurally-inflated-by-episodic-recency.warrant.json
# Markdown SHA-256:   3fd9af9f18780c6d05dc30c5ab649cc213e178fdf39555bab6d5e17846bb90f3
# Code AST SHA-256:   21375fa76028d1b5fd3f23b317fbce83e27de8ff4e110d1fa3e4a1e7dea720dd
# Verified Classes:   ProceduralPromotionError, EpisodicTrace, SemanticFact
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class ProceduralPromotionError(RuntimeError):
    """Raised when a semantic fact is promoted to procedural without sufficient evidence diversity."""
    pass


@dataclass(frozen=True)
class EpisodicTrace:
    world_state_hash: str
    observed_at: float
    succeeded: bool


@dataclass(frozen=True)
class SemanticFact:
    key: str
    value: str
    traces: Sequence[EpisodicTrace]


def effective_cluster_count(traces: Sequence[EpisodicTrace]) -> int:
    """Count distinct world-states, not raw hit count. Repeated observation of one
    world-state contributes one unit of evidence regardless of how many traces it produced."""
    return len({t.world_state_hash for t in traces if t.succeeded})


def promote_to_procedural(fact: SemanticFact, min_clusters: int = 3) -> str:
    clusters = effective_cluster_count(fact.traces)
    hits = sum(1 for t in fact.traces if t.succeeded)

    if clusters < min_clusters:
        raise ProceduralPromotionError(
            f"Refusing to promote {fact.key!r} to procedural: "
            f"{hits} successful traces but only {clusters} distinct world-state cluster(s); "
            f"required >= {min_clusters}. Recency bias in retrieval confidence does not "
            f"substitute for evidence diversity. Fact remains semantic and verifiable."
        )

    return f"procedure:{fact.key} -> {fact.value} (compiled over {clusters} clusters, verify_on_use=False)"
