# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-promote-an-episodic-trace-into-semantic-memory-when-the-consolidation-summarizer-and-the-retrieval-sc.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-promote-an-episodic-trace-into-semantic-memory-when-the-consolidation-summarizer-and-the-retrieval-sc.warrant.json
# Markdown SHA-256:   32bc1c8b650b9585a067e8ca6c47d5574f53ab4e101d8e1815295a3450fe0f5f
# Code AST SHA-256:   1e9fd9983f066cbf09f4eb7f8f929bd2adbc66a67272a86e9e39729854b726cf
# Verified Classes:   PromotionRefused, Candidate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence

TAU_RECALL = 0.60
TAU_PRECISION = 0.50


class PromotionRefused(RuntimeError):
    """Raised when an episodic cluster may not be promoted to semantic memory."""


@dataclass
class Candidate:
    text: str
    source_ids: Sequence[str]
    has_external_anchor: bool


def round_trip_metrics(candidate: Candidate, retrieve_fn) -> tuple[float, float]:
    """Return (recall, precision) of top-k retrieval against source episodes."""
    hits = retrieve_fn(candidate.text, k=10)
    hit_ids = {h.id for h in hits}
    src = set(candidate.source_ids)
    recall = len(hit_ids & src) / len(src) if src else 0.0
    precision = len(hit_ids & src) / max(len(hit_ids), 1)
    return recall, precision


def promote_or_refuse(candidate: Candidate, retrieve_fn) -> str:
    recall, precision = round_trip_metrics(candidate, retrieve_fn)
    reachable = recall >= TAU_RECALL and precision >= TAU_PRECISION

    if reachable:
        return "promote:provenance=episodic_roundtrip"

    if candidate.has_external_anchor:
        # Reachability via episodic path is broken, but an anchor substitutes.
        return "promote:provenance=external_anchor:retrieval_path=anchor_only"

    # Condition 1 (abstraction drift) is implied by failed round-trip when no
    # anchor exists; refuse and route to re-representation, never discard.
    raise PromotionRefused(
        f"candidate {candidate.text!r} failed round-trip "
        f"(recall={recall:.2f}, precision={precision:.2f}); "
        f"quarantine and re-represent into episodic register"
    )
