# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-consolidate-a-cross-session-episodic-contradiction-into-semantic-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-consolidate-a-cross-session-episodic-contradiction-into-semantic-memory.warrant.json
# Markdown SHA-256:   7f0f71160e3a6fad5fc94fd3c458e9b0d6f6e7e7040aa21850c48fe64d69df28
# Code AST SHA-256:   2bfc38621ea74e9e3f62d6107e2f1897bfe21c30acefd3b440a65071254ed1fe
# Verified Classes:   ConsolidationRefused, Warrant, Episode, SemanticFact
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class ConsolidationRefused(RuntimeError):
    """Raised when a distiller attempts to resolve a contradiction without a warrant."""
    pass


class Warrant(Enum):
    CAUSAL_SUPERSESSION = "causal_supersession"
    SOURCE_AUTHORITY = "source_authority"
    EXPLICIT_USER_RESOLUTION = "explicit_user_resolution"


@dataclass
class Episode:
    session_id: int
    source: str
    value: str
    confidence: float
    supersedes_prior: bool = False  # records an action invalidating earlier value


@dataclass
class SemanticFact:
    entity: str
    attribute: str
    values: set
    status: str  # "resolved" | "unresolved"
    evidence: list = field(default_factory=list)


def consolidate(entity: str, attribute: str, episodes: list) -> SemanticFact:
    distinct = {e.value for e in episodes}
    evidence = [e.session_id for e in episodes]

    if len(distinct) <= 1:
        return SemanticFact(entity, attribute, distinct, "resolved", evidence)

    # Contradiction present. Look for a warrant.
    warrant = None
    for e in episodes:
        if e.supersedes_prior:
            warrant = Warrant.CAUSAL_SUPERSESSION
            break

    if warrant is None:
        # No warrant: refuse to fabricate a resolution. Emit a conflict record
        # and preserve all evidence (do NOT prune the losing traces).
        return SemanticFact(entity, attribute, distinct, "unresolved", evidence)

    # A warrant exists: the distiller may resolve, but must cite the warrant
    # and must retain the superseded traces until the warrant is confirmed.
    latest = max(episodes, key=lambda e: e.session_id)
    return SemanticFact(entity, attribute, {latest.value}, "resolved", evidence)


def distill_or_refuse(entity: str, attribute: str, episodes: list) -> SemanticFact:
    fact = consolidate(entity, attribute, episodes)
    if fact.status == "unresolved" and len(fact.values) > 1:
        # Guard: an unresolved multi-valued key must never be coerced to a
        # single value by a downstream recency/frequency heuristic.
        raise ConsolidationRefused(
            f"{entity}.{attribute} has {len(fact.values)} evidentially-distinct "
            f"values {sorted(fact.values)} with no supersession warrant; "
            f"refusing to consolidate. Evidence retained: {fact.evidence}"
        )
    return fact


# Demonstration of the boundary trigger from the record:
# eps = [
#     Episode(12, "tool:terraform_state", "us-east-1", 0.95),
#     Episode(19, "tool:terraform_state", "eu-west-1", 0.95),
#     Episode(31, "user:ops-lead", "us-east-1", 0.60),
#     Episode(44, "tool:terraform_state", "eu-west-1", 0.95),
# ]
# distill_or_refuse("svc-checkout", "primary_region", eps)
# -> raises ConsolidationRefused (no episode carries supersedes_prior=True)
