# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-poisoned-semantic-memory-when-the-poisoning-vector-is-a-legitimate-distillation-of-a-hostile-episode.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-poisoned-semantic-memory-when-the-poisoning-vector-is-a-legitimate-distillation-of-a-hostile-episode.warrant.json
# Markdown SHA-256:   1677aeacf30221ccb44f2bc88ece078d002e92a5a304d9c6c34e815845f1f704
# Code AST SHA-256:   fb6d10636ae0beff19511f59638764f58b77923c0742003aa3614320b2f486fd
# Verified Classes:   WarrantPreservationError, DistillationResult, MemoryEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class WarrantPreservationError(RuntimeError):
    """Raised when a distilled memory entry cannot satisfy the warrant-preservation invariant."""
    pass


@dataclass
class DistillationResult:
    rule: str
    evidence_spans: list[str]
    counter_evidence_spans: list[str]
    dismissal_rationale: Optional[str]
    source_episode_ids: list[str]
    confidence: float


@dataclass
class MemoryEntry:
    rule: str
    source_episode_ids: list[str]
    confidence: float
    warrant_complete: bool
    tier: str = field(default="quarantine")


def admit_distilled_entry(result: DistillationResult, authoritative_corpus: dict[str, str]) -> MemoryEntry:
    # The invariant: a distilled rule is only trusted if its warrant record is
    # reconstructible AND any counter-evidence it dismissed is reconciled against
    # the authoritative corpus. Confidence is deliberately NOT part of this check.
    if not result.source_episode_ids:
        raise WarrantPreservationError("distilled entry has no source episode; warrant unreconstructible")

    if result.counter_evidence_spans and not result.dismissal_rationale:
        raise WarrantPreservationError(
            f"entry '{result.rule}' dismissed counter-evidence "
            f"{result.counter_evidence_spans} without a dismissal rationale; "
            "warrant is laundered and entry must not be trusted"
        )

    for span in result.counter_evidence_spans:
        if span not in authoritative_corpus.values():
            raise WarrantPreservationError(
                f"counter-evidence span '{span}' is not present in the authoritative corpus; "
                "reconciliation cannot be performed, entry stays quarantined"
            )

    warrant_complete = bool(result.evidence_spans) and (
        not result.counter_evidence_spans or bool(result.dismissal_rationale)
    )

    return MemoryEntry(
        rule=result.rule,
        source_episode_ids=result.source_episode_ids,
        confidence=result.confidence,
        warrant_complete=warrant_complete,
        tier="trusted" if warrant_complete else "quarantine",
    )


def retrieve_with_obligation(entry: MemoryEntry, corpus_slice: Optional[str]) -> tuple[MemoryEntry, Optional[str]]:
    # Quarantined entries may be surfaced but MUST co-fetch the authoritative
    # corpus slice so the consuming reasoning step can reconcile before acting.
    if entry.tier == "quarantine" and corpus_slice is None:
        raise WarrantPreservationError(
            f"quarantined entry '{entry.rule}' surfaced without mandatory corpus co-fetch; "
            "poisoned rule could preempt its own contradiction"
        )
    return entry, corpus_slice
