# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-decayed-graph-edge-whose-vector-twin-has-already-been-re-embedded-the-temporal-skew-contradiction-trap-in-hybrid-me.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-decayed-graph-edge-whose-vector-twin-has-already-been-re-embedded-the-temporal-skew-contradiction-trap-in-hybrid-me.warrant.json
# Markdown SHA-256:   bd03a61df161da31745103628f64df94b8d5cf5c06f31abefa3fc8a9618e9de0
# Code AST SHA-256:   6bf5a80002ce51a874df1d8e059e8d3498448215d02cf87e4aa7571946e733bb
# Verified Classes:   TemporalSkewResolutionError, Candidate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass


class TemporalSkewResolutionError(RuntimeError):
    """Raised when a resolver attempts to compare memory candidates
    that share no fact-version clock (tau). Cross-tau voting is invalid."""


@dataclass
class Candidate:
    source: str          # "vector" | "graph"
    fact_id: str
    value: str
    tau: int             # fact-version clock, NOT embed time
    score: float         # similarity or decayed confidence


DECAY_LAMBDA = 0.15


def decayed_confidence(base: float, age_sessions: int) -> float:
    return base * math.exp(-DECAY_LAMBDA * age_sessions)


def resolve(candidates: list[Candidate]) -> Candidate:
    if not candidates:
        raise TemporalSkewResolutionError("no candidates to resolve")

    taus = {c.tau for c in candidates}
    if len(taus) > 1:
        # A vector and graph disagree on which fact-version they encode.
        # This is either a lagging projection (graph newer) or a torn write
        # (vector newer). Never vote across the boundary.
        graph_taus = {c.tau for c in candidates if c.source == "graph"}
        vector_taus = {c.tau for c in candidates if c.source == "vector"}
        if graph_taus and vector_taus and max(vector_taus) > max(graph_taus):
            raise TemporalSkewResolutionError(
                f"torn write: vector tau={max(vector_taus)} ahead of "
                f"graph tau={max(graph_taus)} for fact "
                f"{candidates[0].fact_id}; halt and reconcile, do not guess"
            )
        # Graph is authoritative for currency: drop lagging vector projections.
        candidates = [c for c in candidates if c.source == "graph"]
        if not candidates:
            raise TemporalSkewResolutionError(
                "all candidates were lagging vector projections; "
                "re-embed from graph before resolving"
            )

    # Same tau: safe to compare by score.
    return max(candidates, key=lambda c: c.score)


def resolve_or_fail(candidates: list[Candidate]) -> Candidate:
    try:
        return resolve(candidates)
    except TemporalSkewResolutionError:
        # Surface the contradiction to the caller rather than emitting a
        # confidently wrong answer that will compound via reinforcement.
        raise
