# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-promote-episodic-memory-to-semantic-memory-when-retrieval-time-conflict-resolution-would-otherwise-ov.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-promote-episodic-memory-to-semantic-memory-when-retrieval-time-conflict-resolution-would-otherwise-ov.warrant.json
# Markdown SHA-256:   b3d649d6058e634ac54f0fa041eee94267b02f4fe85171db685f4eed6d09fd86
# Code AST SHA-256:   c8ff3204b0501c4f5ccc506b298bf4e599b0ac8c189c38d4f2107469c7c07962
# Verified Classes:   PromotionConflictError, EpisodicTrace, SemanticClaim, Cluster
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class PromotionConflictError(RuntimeError):
    """Raised when a lossy promotion would collapse a live episodic contradiction."""
    pass


@dataclass
class EpisodicTrace:
    instance_id: str
    step: int
    key: str
    value: object
    qualifiers: dict          # e.g. {"deployment": "staging"}
    raw_output: str


@dataclass
class SemanticClaim:
    key: str
    value: object
    qualifiers: dict
    confidence: float
    source_steps: list
    promoted_at: int


@dataclass
class Cluster:
    key: str
    members: list = field(default_factory=list)


CLAIM_SCHEMA_QUALIFIERS = {"deployment"}   # fields the claim schema can carry


def promote(cluster: Cluster, promoted_at: int) -> list:
    """Promote an episodic cluster to semantic claims, or refuse if lossy."""
    if not cluster.members:
        raise PromotionConflictError(f"empty cluster for key {cluster.key!r}")

    # Identify fields on which members disagree.
    disagreeing = set()
    base = cluster.members[0].qualifiers
    for m in cluster.members[1:]:
        for k in set(base) | set(m.qualifiers):
            if base.get(k) != m.qualifiers.get(k):
                disagreeing.add(k)

    unrepresentable = disagreeing - CLAIM_SCHEMA_QUALIFIERS
    if unrepresentable:
        # Invariant violation: promotion would strip a disambiguating field.
        # Refuse; caller must retain raw traces and mark the key contested.
        raise PromotionConflictError(
            f"cannot promote cluster {cluster.key!r}: members disagree on "
            f"{sorted(unrepresentable)}, which the claim schema cannot carry. "
            f"Retain episodic traces and mark contested."
        )

    # Safe: emit one claim per distinct (value, qualifier) combination.
    claims = []
    for m in cluster.members:
        claims.append(SemanticClaim(
            key=cluster.key,
            value=m.value,
            qualifiers={k: m.qualifiers[k] for k in CLAIM_SCHEMA_QUALIFIERS
                        if k in m.qualifiers},
            confidence=0.6,
            source_steps=[m.step],
            promoted_at=promoted_at,
        ))
    return claims


def resolve(semantic: list, episodic: list) -> list:
    """Retrieval-time conflict resolution over the merged partitions."""
    for s in semantic:
        # Guard: any claim whose provenance no longer resolves is untrusted.
        if not s.source_steps:
            raise PromotionConflictError(
                f"claim {s.key!r}={s.value!r} has no reachable provenance; "
                f"demote to contested rather than let it win precedence."
            )
    # Qualified claims do not contradict; surface all of them.
    return semantic + episodic


def nightly_distill(clusters: list, promoted_at: int) -> list:
    out = []
    for c in clusters:
        try:
            out.extend(promote(c, promoted_at))
        except PromotionConflictError:
            # Keep the raw episodic traces; do not manufacture a conclusion.
            out.extend(EpisodicTrace(
                instance_id=m.instance_id, step=m.step, key=m.key,
                value=m.value, qualifiers=m.qualifiers, raw_output=m.raw_output,
            ) for m in c.members)
    return out
