# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-episodic-to-semantic-distillation-from-silently-rewriting-the-agent-s-own-audit-trail.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-episodic-to-semantic-distillation-from-silently-rewriting-the-agent-s-own-audit-trail.warrant.json
# Markdown SHA-256:   3ef4fa222fb693bfb68e39ce78cf00ecabd4f99c1fdd9e27496ef697b5a41ab0
# Code AST SHA-256:   7fcb25022effb5f98986c7d0ba053f6cb646146d36e45d379700ad9b77e8ef11
# Verified Classes:   ProvenanceInvariantError, SemanticFact, MemoryTier
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ProvenanceInvariantError(RuntimeError):
    """Raised when a semantic fact would outlive or lose its episodic evidence."""


@dataclass(frozen=True)
class SemanticFact:
    fact_id: str
    assertion: str
    provenance: FrozenSet[int]          # episode IDs
    confidence_state: str = "provisional"  # verified | provisional | contested
    minted_at_step: int = 0


@dataclass
class MemoryTier:
    episodes: dict = field(default_factory=dict)      # id -> raw record
    facts: dict = field(default_factory=dict)         # fact_id -> SemanticFact
    contradiction_ledger: list = field(default_factory=list)


def evict_episodes(tier: MemoryTier, evict_ids: FrozenSet[int]) -> None:
    """Evict raw episodes, but refuse if any live fact depends on them
    and has not been re-verified against a resolvable provenance set."""
    for fact in tier.facts.values():
        if fact.provenance & evict_ids:
            if fact.confidence_state != "verified":
                raise ProvenanceInvariantError(
                    f"refusing to evict {sorted(evict_ids & fact.provenance)}: "
                    f"fact {fact.fact_id} is '{fact.confidence_state}' and would "
                    f"lose its only evidence. Re-verify or demote first."
                )
            # verified facts may still not lose *all* provenance
            if fact.provenance <= evict_ids:
                raise ProvenanceInvariantError(
                    f"refusing to evict full provenance of verified fact "
                    f"{fact.fact_id}; retention horizon of evidence must "
                    f"dominate retention horizon of conclusion."
                )
    for eid in evict_ids:
        tier.episodes.pop(eid, None)


def mint_fact(tier: MemoryTier, fact: SemanticFact, entailment_ok: bool) -> None:
    """Mint a semantic fact only if its provenance resolves and a fresh
    verifier (not shown the prior semantic store) confirmed entailment."""
    missing = [eid for eid in fact.provenance if eid not in tier.episodes]
    if missing:
        raise ProvenanceInvariantError(
            f"cannot mint {fact.fact_id}: provenance episodes {missing} "
            f"already evicted — fact would be unfalsifiable."
        )
    if not entailment_ok:
        raise ProvenanceInvariantError(
            f"cannot mint {fact.fact_id} as verified: fresh verifier did not "
            f"confirm entailment from provenance {sorted(fact.provenance)}."
        )
    tier.facts[fact.fact_id] = SemanticFact(
        fact_id=fact.fact_id,
        assertion=fact.assertion,
        provenance=fact.provenance,
        confidence_state="verified",
        minted_at_step=fact.minted_at_step,
    )


def record_contradiction(tier: MemoryTier, fact_id: str, episode_id: int) -> None:
    """Any contradicting episode demotes the fact and forces re-distillation
    with the contradicting episode included in provenance."""
    fact = tier.facts.get(fact_id)
    if fact is None:
        raise ProvenanceInvariantError(f"unknown fact {fact_id}")
    tier.contradiction_ledger.append((fact_id, episode_id))
    tier.facts[fact_id] = SemanticFact(
        fact_id=fact.fact_id,
        assertion=fact.assertion,
        provenance=fact.provenance | {episode_id},
        confidence_state="contested",
        minted_at_step=fact.minted_at_step,
    )
