# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-provenance-degraded-memory-writes-before-contradiction-tracking-can-distinguish-poisoning-from-legitimat.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-provenance-degraded-memory-writes-before-contradiction-tracking-can-distinguish-poisoning-from-legitimat.warrant.json
# Markdown SHA-256:   28b29faa6b3d5b4b31097b4a34ed9878feb1a91b1f46a58fbb6f9e119e4e5474
# Code AST SHA-256:   7e723f5db70134b56807df6a1501d0af005fe9a629a1199c9300abf6be007b2b
# Verified Classes:   ProvenanceError, Resolution, Belief
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class ProvenanceError(RuntimeError):
    """Raised when a memory write's provenance chain is missing or non-monotone."""
    pass


class Resolution(Enum):
    QUARANTINE_LOW = "quarantine_low"
    RETAIN_HIGH = "retain_high"
    ESCALATE = "escalate"


@dataclass
class Belief:
    claim: str
    weight: float
    provenance_chain: list = field(default_factory=list)


def resolve_contradiction(a: Belief, b: Belief, tau: float = 0.3) -> Resolution:
    # Missing provenance is maximum ambiguity, never trusted default.
    if not a.provenance_chain or not b.provenance_chain:
        return Resolution.ESCALATE
    gap = abs(a.weight - b.weight)
    if gap > tau:
        return Resolution.QUARANTINE_LOW
    return Resolution.ESCALATE


def consolidate(belief: Belief, transformer: str, re_verified: bool) -> Belief:
    # Provenance weight must be non-increasing unless an independent
    # verification event re-establishes it. Laundering is blocked here.
    if not belief.provenance_chain:
        raise ProvenanceError(
            f"cannot consolidate {belief.claim!r}: missing provenance chain"
        )
    new_weight = belief.weight if not re_verified else min(1.0, belief.weight)
    if new_weight > belief.weight:
        raise ProvenanceError(
            f"consolidation by {transformer} attempted to raise provenance "
            f"{belief.weight} -> {new_weight} without verification"
        )
    chain = belief.provenance_chain + [{"hop": transformer, "verified": re_verified}]
    return Belief(belief.claim, new_weight, chain)


def apply_resolution(a: Belief, b: Belief, tau: float = 0.3) -> dict:
    res = resolve_contradiction(a, b, tau)
    if res is Resolution.QUARANTINE_LOW:
        low, high = (a, b) if a.weight < b.weight else (b, a)
        return {"action": res, "quarantined": low.claim, "retained": high.claim}
    if res is Resolution.ESCALATE:
        return {"action": res, "contested": [a.claim, b.claim]}
    raise ProvenanceError("unreachable resolution state")
