# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-provenance-clean-memory-record-whose-trust-score-has-decayed-below-its-admission-threshold.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-provenance-clean-memory-record-whose-trust-score-has-decayed-below-its-admission-threshold.warrant.json
# Markdown SHA-256:   474cffe2000d05757c0067d3b36d796d520d6fd564e1b5e9aadf2b167433a0a9
# Code AST SHA-256:   f1e7ad5fce1f130f6a054b09147b1b49b0d2835483152611a5e88ccb706bae3a
# Verified Classes:   GateInversionError, DecayClass, MemoryRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class GateInversionError(RuntimeError):
    """Raised when bulk decay of a stable-class cluster outranks its replacement."""


class DecayClass(Enum):
    VOLATILE = "volatile"
    STABLE = "stable"


@dataclass
class MemoryRecord:
    id: str
    claim: str
    trust_score: float
    provenance_weight: float
    decay_class: DecayClass
    last_corroborated_day: int
    quarantined: bool = False


ADMISSION_THRESHOLD = 0.55
RETENTION_THRESHOLD = 0.40


def retrieve(records, query_authority, current_day):
    admitted = [
        r for r in records
        if not r.quarantined and r.trust_score >= ADMISSION_THRESHOLD
    ]
    filtered = [
        r for r in records
        if not r.quarantined and RETENTION_THRESHOLD <= r.trust_score < ADMISSION_THRESHOLD
    ]

    if admitted:
        top_provenance = max(r.provenance_weight for r in admitted)
    else:
        top_provenance = 0.0

    stable_filtered = [r for r in filtered if r.decay_class is DecayClass.STABLE]
    if stable_filtered:
        filtered_provenance = max(r.provenance_weight for r in stable_filtered)
        bulk_decay = len(stable_filtered) >= 10
        if bulk_decay and filtered_provenance > top_provenance:
            raise GateInversionError(
                f"Gate inversion: {len(stable_filtered)} stable-class records "
                f"(max provenance {filtered_provenance:.2f}) filtered below "
                f"admission while replacement cluster has provenance "
                f"{top_provenance:.2f}. Re-verify before acting; do not lower threshold."
            )

    return admitted if admitted else filtered


def re_verify_and_resolve(records, ground_truth_fn, current_day):
    for r in records:
        if r.trust_score < ADMISSION_THRESHOLD and r.decay_class is DecayClass.STABLE:
            if ground_truth_fn(r.claim):
                r.trust_score = min(1.0, r.trust_score + 0.30)
                r.last_corroborated_day = current_day
                r.quarantined = False
            else:
                r.quarantined = True
    return records
