# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-store-poisoning-when-episodic-evidence-has-already-been-distilled-away.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-store-poisoning-when-episodic-evidence-has-already-been-distilled-away.warrant.json
# Markdown SHA-256:   7960de56765b227cc75c2491e8d642415473a12290b3bddb2f798e63934a619b
# Code AST SHA-256:   24ea17543b8f5cf9536f0f69ec1d1cd40ff41d5b80d3f09f96953e2b19057b73
# Verified Classes:   ProvenanceIntegrityError, Derivation, CompactionEvent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ProvenanceIntegrityError(RuntimeError):
    """Raised when a semantic fact's derivation cannot be structurally validated."""
    pass


@dataclass(frozen=True)
class Derivation:
    fact_id: str
    episode_ids: tuple[str, ...]
    distilled_at: float          # monotonic event clock
    asserted_confidence: float
    distiller_version: str


@dataclass(frozen=True)
class CompactionEvent:
    episode_id: str
    compacted_at: float
    digest_sha256: str


COMPACTED_CONFIDENCE_CEILING = 0.60


def check_fact_integrity(
    deriv: Derivation,
    compactions: dict[str, CompactionEvent],
    raw_episodes_live: set[str],
) -> str:
    """
    Returns 'clean', 'clean_degraded', or raises ProvenanceIntegrityError.
    Never treats a digest as independent corroboration.
    """
    if not deriv.episode_ids:
        raise ProvenanceIntegrityError(
            f"fact {deriv.fact_id}: empty derivation set — no provenance anchor"
        )

    has_live_raw = any(eid in raw_episodes_live for eid in deriv.episode_ids)
    only_compacted = all(eid in compactions for eid in deriv.episode_ids)

    # Structural invariant (b): a fact cannot be distilled from an episode
    # that was already destroyed. Backdated/forged derivations trip this.
    for eid in deriv.episode_ids:
        ev = compactions.get(eid)
        if ev is not None and ev.compacted_at < deriv.distilled_at:
            raise ProvenanceIntegrityError(
                f"fact {deriv.fact_id}: cites episode {eid} compacted at "
                f"{ev.compacted_at} but claims distillation at {deriv.distilled_at} "
                f"— temporal impossibility, probable forged write"
            )

    if has_live_raw:
        return "clean"

    if only_compacted:
        # Structural invariant (a): confidence ceiling for compacted sources.
        if deriv.asserted_confidence > COMPACTED_CONFIDENCE_CEILING:
            raise ProvenanceIntegrityError(
                f"fact {deriv.fact_id}: confidence {deriv.asserted_confidence} "
                f"exceeds ceiling {COMPACTED_CONFIDENCE_CEILING} for "
                f"compacted-only provenance — quarantine required"
            )
        return "clean_degraded"

    # Mixed or unknown provenance state: cannot certify.
    raise ProvenanceIntegrityError(
        f"fact {deriv.fact_id}: provenance state indeterminate "
        f"(live_raw={has_live_raw}, only_compacted={only_compacted})"
    )


def gate_retrieval(deriv: Derivation, compactions, raw_live) -> bool:
    try:
        status = check_fact_integrity(deriv, compactions, raw_live)
    except ProvenanceIntegrityError:
        return False  # quarantine: do not act
    return status in ("clean", "clean_degraded")
