# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-treats-a-contradiction-between-two-equally-provenanced-memories-as-noise-and-resolves-it-by-recency.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-treats-a-contradiction-between-two-equally-provenanced-memories-as-noise-and-resolves-it-by-recency.warrant.json
# Markdown SHA-256:   2dd1bac5fdd80e8949fc538fd6f06a678d28eb22814f6ce7bbe44896d9abac40
# Code AST SHA-256:   78100263487f22293e73abbdf1446e8ae717aca7e7632e9eb66ca0ba137e910a
# Verified Classes:   TrustTier, ContradictionUnresolved, WarrantVerificationError, MemoryRecord, RecallResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class TrustTier(IntEnum):
    T2 = 2  # peer attestation, unsigned
    T1 = 1  # verified tool output, signed by tool warrant
    T0 = 0  # operator-authored, signed by operator key

    # Lower numeric value == higher trust. Selection picks min tier.


class ContradictionUnresolved(RuntimeError):
    """Raised when a contradiction class has no unique maximal-tier record
    after warrant verification. The recall path must fail closed: the agent
    is not authorized to resolve the conflict by similarity or recency."""


class WarrantVerificationError(RuntimeError):
    """Raised when a record's claimed tier cannot be backed by a verified
    warrant. The record is demoted, not trusted at its claimed tier."""


@dataclass(frozen=True)
class MemoryRecord:
    subject: str
    value: str
    claimed_tier: TrustTier
    ts: int
    author: str
    signature: Optional[str] = None
    derived_from: Optional[str] = None  # record id, if this is a derived observation


@dataclass
class RecallResult:
    subject: str
    value: str
    tier: TrustTier
    excluded_dominated: list = field(default_factory=list)


def verify_warrant(rec: MemoryRecord, trusted_keys: dict) -> TrustTier:
    """Return the *verified* tier. A record claiming T0 or T1 without a
    signature that verifies against a trusted key is demoted to T2."""
    if rec.claimed_tier in (TrustTier.T0, TrustTier.T1):
        if rec.signature is None or trusted_keys.get(rec.author) is None:
            return TrustTier.T2
        # In production: cryptographic verify(rec.signature, trusted_keys[rec.author])
        if not rec.signature.startswith(trusted_keys[rec.author]):
            return TrustTier.T2
    return rec.claimed_tier


def resolve_contradiction_class(
    subject: str,
    records: list,
    trusted_keys: dict,
) -> RecallResult:
    """Enforce the invariant: select() is a singleton at the maximal verified
    tier, or ContradictionUnresolved. Never a scored winner."""
    if not records:
        raise ContradictionUnresolved(f"no records for subject={subject!r}")

    # Step 1: demote any record whose warrant does not verify.
    verified = [(r, verify_warrant(r, trusted_keys)) for r in records]

    # Step 2: find the maximal verified tier present.
    best_tier = min(t for _, t in verified)

    # Step 3: candidate set is records at the maximal tier.
    maximal = [(r, t) for r, t in verified if t == best_tier]

    # Step 4: drop derived records whose source is also in the class —
    # they double-count one underlying observation.
    source_ids = {r.author + ":" + str(r.ts) for r, _ in maximal}
    independent = [
        (r, t) for r, t in maximal
        if r.derived_from is None or r.derived_from not in source_ids
    ]
    if not independent:
        independent = maximal  # all derived; fall back to full maximal set

    # Step 5: singleton or fail closed. No similarity, no recency tiebreak.
    distinct_values = {r.value for r, _ in independent}
    if len(distinct_values) > 1:
        raise ContradictionUnresolved(
            f"subject={subject!r} has {len(distinct_values)} incompatible "
            f"values at maximal tier {best_tier.name}: "
            f"{sorted(distinct_values)}; refusing to select by similarity"
        )

    chosen, chosen_tier = independent[0]
    excluded = [r for r, t in verified if t != best_tier]
    return RecallResult(
        subject=subject,
        value=chosen.value,
        tier=chosen_tier,
        excluded_dominated=excluded,
    )


def recall(subject: str, store: list, trusted_keys: dict) -> RecallResult:
    class_records = [r for r in store if r.subject == subject]
    return resolve_contradiction_class(subject, class_records, trusted_keys)
