# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-poisoned-memory-provenance-decay-across-episodic-to-semantic-distillation-in-long-term-vector-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-poisoned-memory-provenance-decay-across-episodic-to-semantic-distillation-in-long-term-vector-stores.warrant.json
# Markdown SHA-256:   89a12196a856be451947fe28a0b0910289e18ebbf0ab077869b0670e64f2ca26
# Code AST SHA-256:   c08414c62ee80eb3e14cbc8de881d51b7a8a221fbfee533ceffd143d1cbb34af
# Verified Classes:   Trust, ProvenanceDecayError, Episode, SemanticRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import IntEnum


class Trust(IntEnum):
    UNTRUSTED = 0
    SELF_REFLECTION = 1
    VERIFIED = 2
    AUTHORITATIVE = 3


class ProvenanceDecayError(RuntimeError):
    """Raised when distillation would promote a record above its weakest ancestor."""


@dataclass(frozen=True)
class Episode:
    episode_id: str
    source: str
    trust: Trust


@dataclass(frozen=True)
class SemanticRecord:
    text: str
    asserted_trust: Trust
    ancestor_ids: tuple[str, ...]


def gate_distillation(
    record: SemanticRecord,
    episodic_log: dict[str, Episode],
) -> Trust:
    """Enforce semantic trust <= min(episodic ancestor trust).

    Rejects orphaned chains, self-reflection ancestors, and any promotion
    above the weakest verified ancestor. Returns the capped trust tier.
    """
    if not record.ancestor_ids:
        raise ProvenanceDecayError(
            f"orphaned semantic record {record.text!r}: no provenance chain; "
            "distillation stripped all ancestor IDs"
        )

    missing = [a for a in record.ancestor_ids if a not in episodic_log]
    if missing:
        raise ProvenanceDecayError(
            f"broken provenance chain for {record.text!r}: "
            f"unknown ancestor episodes {missing}"
        )

    ancestors = [episodic_log[a] for a in record.ancestor_ids]

    if any(ep.source == "self_reflection" for ep in ancestors):
        raise ProvenanceDecayError(
            f"self-reflection used as corroborating ancestor for {record.text!r}; "
            "reflections must not feed the semantic store (amplification loop)"
        )

    weakest = min(ep.trust for ep in ancestors)
    if record.asserted_trust > weakest:
        raise ProvenanceDecayError(
            f"provenance decay: record {record.text!r} asserts "
            f"{record.asserted_trust.name} but weakest ancestor is {weakest.name}"
        )

    return weakest
