# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-embedding-space-drift-has-silently-corrupted-a-hybrid-episodic-semantic-memory-store-s-conflict-resolution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-embedding-space-drift-has-silently-corrupted-a-hybrid-episodic-semantic-memory-store-s-conflict-resolution.warrant.json
# Markdown SHA-256:   9e2fb8efcfd7fb6e488111f97867d6542ae2ef28fabebfcfdd15d6532bab95b9
# Code AST SHA-256:   b71e06569dd17519531a48ddb3b85f90ab587f761b982757cf48a7d77c731fb1
# Verified Classes:   VintageDriftViolation, ClusterStats
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import numpy as np
from dataclasses import dataclass

class VintageDriftViolation(RuntimeError):
    """Raised when cross-vintage embedding distances invalidate conflict resolution."""
    pass

@dataclass
class ClusterStats:
    d_within_p99: float      # p99 distance among same-proposition, same-vintage pairs
    d_cross_median: float    # median distance among same-proposition, cross-vintage pairs
    d_contradiction_min: float  # min distance among known contradiction pairs (post-upgrade)

def assert_resolution_sound(stats: ClusterStats, merge_threshold: float) -> None:
    # Invariant 1: cross-vintage same-fact distance must stay below the merge margin,
    # else genuine updates get inserted as duplicates.
    if stats.d_cross_median >= merge_threshold:
        raise VintageDriftViolation(
            f"cross-vintage same-fact distance {stats.d_cross_median:.3f} >= "
            f"merge threshold {merge_threshold:.3f}: updates will duplicate, not merge"
        )
    # Invariant 2: the merge threshold must stay strictly below the closest
    # contradiction distance, else contradictions get merged (destructive).
    if merge_threshold >= stats.d_contradiction_min:
        raise VintageDriftViolation(
            f"merge threshold {merge_threshold:.3f} >= nearest contradiction distance "
            f"{stats.d_contradiction_min:.3f}: contradictions will be silently merged"
        )
    # Invariant 3: the vintage valley must be separable from within-vintage spread.
    if stats.d_cross_median <= stats.d_within_p99:
        raise VintageDriftViolation(
            "no vintage boundary detected; calibration probes missing or stale—"
            "cannot certify cross-vintage comparability"
        )

def resolve_conflict(new_vec: np.ndarray, new_vintage: int,
                     existing: list[tuple[np.ndarray, int]],
                     merge_threshold: float) -> str:
    comparable = [(v, vt) for (v, vt) in existing if vt == new_vintage]
    if not comparable:
        # Fail closed: never arbitrate across vintages without calibration.
        raise VintageDriftViolation(
            f"no same-vintage candidates for vintage {new_vintage}; "
            "route to re-embedding, do not merge"
        )
    dists = [float(np.dot(new_vec, v) / (np.linalg.norm(new_vec) * np.linalg.norm(v)))
             for v, _ in comparable]
    best = min(dists)
    return "merge" if best >= merge_threshold else "insert"
