# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-trust-weighted-contradiction-before-consolidation-and-when-is-quarantine-itself-the-poison.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-trust-weighted-contradiction-before-consolidation-and-when-is-quarantine-itself-the-poison.warrant.json
# Markdown SHA-256:   68fee3d14427dc2f2baf99ef3d327ce24bbd09d34dcc66cb0bd4251e02b875bd
# Code AST SHA-256:   abd6642cfccd1180ab80100102df6404a16971dfe1a44cece104b5edfdca9da8
# Verified Classes:   ConsolidationBoundaryError, Claim, Entry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

OVERWRITE_MARGIN = 0.30
FLAG_THRESHOLD = 0.10


class ConsolidationBoundaryError(RuntimeError):
    """Raised when a consolidation decision would violate the availability invariant."""
    pass


@dataclass
class Claim:
    key: str
    value: str
    source_id: str
    trust: float
    lineage_root: str
    epoch: int


@dataclass
class Entry:
    claim: Claim
    disputed: bool = False
    dissent: list = field(default_factory=list)
    quarantined: bool = False


def consolidate(new: Claim, existing: Optional[Entry],
                integrity_flag: bool = False) -> Entry:
    # Safety events (lineage/injection) are the ONLY quarantine trigger.
    if integrity_flag:
        if existing is not None and existing.claim.trust > new.trust:
            existing.disputed = True
            existing.dissent.append(new.source_id)
            return existing  # keep high-trust fact retrievable
        return Entry(claim=new, quarantined=True)

    if existing is None:
        return Entry(claim=new)

    old = existing.claim
    delta = new.trust - old.trust

    if delta > OVERWRITE_MARGIN:
        if new.lineage_root == old.lineage_root:
            # Re-derivation from same root is not independent corroboration.
            raise ConsolidationBoundaryError(
                f"overwrite of {new.key} by {new.source_id} rejected: "
                f"lineage_root collision with existing entry"
            )
        return Entry(claim=new)

    if -delta > OVERWRITE_MARGIN:
        # Low-trust contradiction of high-trust fact: suppress, do NOT quarantine.
        existing.disputed = True
        existing.dissent.append(new.source_id)
        return existing

    if abs(delta) <= OVERWRITE_MARGIN:
        # Ambiguous: annotate both, require independent corroboration to resolve.
        existing.disputed = True
        existing.dissent.append(new.source_id)
        if new.source_id == old.source_id:
            raise ConsolidationBoundaryError(
                f"self-corroboration attempt on {new.key} by {new.source_id}"
            )
        return existing

    raise ConsolidationBoundaryError(f"unreachable consolidation state for {new.key}")
