# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-consolidate-the-merge-commit-boundary-in-cross-session-memory-deduplication.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-consolidate-the-merge-commit-boundary-in-cross-session-memory-deduplication.warrant.json
# Markdown SHA-256:   8f234474013d2234b8ad40883422101029d996272266203bc76c3da363737ac3
# Code AST SHA-256:   1bec0b1b3cd3750ac7ec644349efbdd87b44e3cde77b7716964b6b405ebeafed
# Verified Classes:   ConsolidationRefused, Resolution, MemoryRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ConsolidationRefused(RuntimeError):
    """Raised when a merge is requested without subject-identity proof."""


class Resolution(Enum):
    MERGE = "merge"
    SUPERSEDE = "supersede"
    KEEP_DISTINCT = "keep_distinct"


@dataclass(frozen=True)
class MemoryRecord:
    subject_key: str          # canonical, normalized entity identifier
    predicate: str
    value: str
    ordering: float | None    # None if clock domain is not comparable
    clock_domain: str


def resolve(new: MemoryRecord, existing: MemoryRecord, cosine: float) -> Resolution:
    # Similarity only routes us here; it never authorizes a merge.
    if new.subject_key != existing.subject_key:
        # Near-duplicate advisory, but the records stay distinct.
        return Resolution.KEEP_DISTINCT

    if new.predicate != existing.predicate:
        raise ConsolidationRefused(
            f"multi-predicate divergence on subject {new.subject_key!r}: "
            f"{existing.predicate!r} vs {new.predicate!r}; "
            "cannot classify as value substitution"
        )

    if new.value == existing.value:
        return Resolution.MERGE  # idempotent no-op merge

    same_clock = (
        new.clock_domain == existing.clock_domain
        and new.ordering is not None
        and existing.ordering is not None
    )
    if not same_clock:
        # Ordering not observable: cannot claim monotonic supersession.
        return Resolution.SUPERSEDE

    if new.ordering <= existing.ordering:
        raise ConsolidationRefused(
            f"non-monotonic merge attempt for {new.subject_key}.{new.predicate}: "
            f"new ordering {new.ordering} <= existing {existing.ordering}"
        )

    return Resolution.MERGE


def consolidate(batch: list[MemoryRecord], store: dict[str, MemoryRecord],
                embed) -> dict[str, MemoryRecord]:
    for rec in batch:
        best, best_sim = None, -1.0
        for key, cand in store.items():
            sim = embed(rec, cand)
            if sim > best_sim:
                best, best_sim = cand, sim

        if best is None or best_sim < 0.88:
            store[f"{rec.subject_key}:{rec.predicate}"] = rec
            continue

        decision = resolve(rec, best, best_sim)
        slot = f"{best.subject_key}:{best.predicate}"

        if decision is Resolution.KEEP_DISTINCT:
            store[f"{rec.subject_key}:{rec.predicate}"] = rec
        elif decision is Resolution.SUPERSEDE:
            # Retain both; conflict edge recorded out-of-band.
            store[f"{rec.subject_key}:{rec.predicate}:v{rec.ordering}"] = rec
        else:  # MERGE
            store[slot] = rec
    return store
