# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-memory-write-that-is-individually-well-formed-but-provenance-inconsistent-with-an-existing-higher-trus.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-memory-write-that-is-individually-well-formed-but-provenance-inconsistent-with-an-existing-higher-trus.warrant.json
# Markdown SHA-256:   7cba1e6e6d298af130d788e6b144fe0fe568b1568abe5101c4d503642e719665
# Code AST SHA-256:   9e9d2f28ef1baa7b2636f4e1cefed348d8d7a8ddb2c75398d5800d46f647c3ca
# Verified Classes:   TrustClass, MemoryEntry, ProvenanceInferiorityError, ReconciliationBudgetExhausted
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Optional


class TrustClass(IntEnum):
    USER_UTTERANCE = 1
    INFERRED = 2
    TOOL_OBSERVED = 3
    WEBHOOK_VERIFIED = 4


@dataclass
class MemoryEntry:
    key: str
    value: str
    trust: TrustClass
    ttl_seconds: int
    age_seconds: int = 0
    derivations: list = field(default_factory=list)
    entry_id: str = ""

    def expired(self) -> bool:
        return self.age_seconds >= self.ttl_seconds


class ProvenanceInferiorityError(RuntimeError):
    """Raised when a well-formed write would lower the trust of a live belief
    without an explicit supersession warrant."""


class ReconciliationBudgetExhausted(RuntimeError):
    """Raised when equal-trust contradiction resolution exceeds its step budget."""


def reconcile_write(
    existing: Optional[MemoryEntry],
    incoming: MemoryEntry,
    supersession_warrant: Optional[str],
    budget_steps: int = 3,
) -> MemoryEntry:
    # TTL evaluated BEFORE trust comparison.
    if existing is None or existing.expired():
        return incoming

    if incoming.value == existing.value:
        merged = existing
        merged.ttl_seconds = max(existing.ttl_seconds, incoming.ttl_seconds)
        merged.derivations = list({*existing.derivations, *incoming.derivations})
        return merged

    # Genuine contradiction from here on.
    if supersession_warrant:
        existing.derivations.append(f"superseded_by:{incoming.entry_id}")
        return incoming

    if incoming.trust < existing.trust:
        raise ProvenanceInferiorityError(
            f"write {incoming.entry_id} (trust={incoming.trust.name}) contradicts "
            f"live entry {existing.entry_id} (trust={existing.trust.name}) "
            f"with no supersession warrant; retained prior belief"
        )

    # Equal-or-higher trust, same class: bounded resolution, never deadlock.
    steps = 0
    while steps < budget_steps:
        steps += 1
        # deterministic tiebreak: higher confidence derivation count wins
        if len(incoming.derivations) > len(existing.derivations):
            return incoming
        if len(incoming.derivations) < len(existing.derivations):
            return existing
        break

    raise ReconciliationBudgetExhausted(
        f"unresolved contradiction between {existing.entry_id} and "
        f"{incoming.entry_id} after {budget_steps} steps; "
        f"route both to auditor, retain existing"
    )
