# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-poisoning-in-its-own-persistent-memory-when-the-poison-is-indistinguishable-from-legitimate-episodic-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-poisoning-in-its-own-persistent-memory-when-the-poison-is-indistinguishable-from-legitimate-episodic-distillation.warrant.json
# Markdown SHA-256:   4cdc37c2fe9bd1a23d04c5e5c9f5838e804c0c02de921d5ebec61c5c0e15c200
# Code AST SHA-256:   d90d33393944e12dbd3cab6ae9e7c37c9e4505d17f76468103ce016d0a7612c6
# Verified Classes:   Trust, ProvenanceLaunderingError, RollbackNonConvergenceError, EpisodicTurn, SemanticEntry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable


class Trust(IntEnum):
    EXTERNAL = 0        # fetched docs, tool output, third-party APIs
    DERIVED = 1         # agent's own summaries of external content
    INTERNAL_USER = 2   # verified user turn
    SYSTEM = 3          # operator-configured invariant


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a semantic promotion would inherit a trust class
    higher than the minimum trust across its episodic provenance closure."""


class RollbackNonConvergenceError(RuntimeError):
    """Raised when a rollback deletes a semantic artifact but leaves a
    promotable episodic source, guaranteeing re-promotion next cycle."""


@dataclass
class EpisodicTurn:
    turn_id: str
    trust: Trust
    revoked: bool = False


@dataclass
class SemanticEntry:
    claim: str
    confidence: float
    derived_from: list[str] = field(default_factory=list)


ADMISSION_THRESHOLD = Trust.INTERNAL_USER


def admit_promotion(
    claim: str,
    confidence: float,
    derived_from: Iterable[str],
    episodic: dict[str, EpisodicTurn],
) -> SemanticEntry:
    """Gate at the trust-transition boundary. Rejects promotion whose
    provenance closure contains any turn below ADMISSION_THRESHOLD or any
    revoked turn. Trust of the result is min over the closure, not the
    destination's default class."""
    closure = list(derived_from)
    if not closure:
        raise ProvenanceLaunderingError(
            f"claim {claim!r} has empty provenance; cannot admit to semantic store"
        )
    min_trust = Trust.SYSTEM
    for tid in closure:
        turn = episodic.get(tid)
        if turn is None:
            raise ProvenanceLaunderingError(
                f"claim {claim!r} cites unknown turn {tid!r}; provenance unverifiable"
            )
        if turn.revoked:
            raise ProvenanceLaunderingError(
                f"claim {claim!r} cites revoked turn {tid!r}; promotion blocked"
            )
        if turn.trust < min_trust:
            min_trust = turn.trust
    if min_trust < ADMISSION_THRESHOLD:
        raise ProvenanceLaunderingError(
            f"claim {claim!r} would inherit semantic trust from provenance "
            f"with min trust {min_trust.name} < {ADMISSION_THRESHOLD.name}; "
            f"refusing to launder external content into semantic memory"
        )
    return SemanticEntry(claim=claim, confidence=confidence, derived_from=closure)


def rollback(
    entry: SemanticEntry,
    episodic: dict[str, EpisodicTurn],
    semantic: list[SemanticEntry],
) -> None:
    """Closure-tainting rollback. Revokes every episodic source in the
    entry's closure and removes the semantic artifact. If the closure is
    not fully revocable, the rollback is non-convergent and must fail
    loudly rather than appear successful."""
    for tid in entry.derived_from:
        turn = episodic.get(tid)
        if turn is None:
            raise RollbackNonConvergenceError(
                f"cannot revoke unknown turn {tid!r} for claim {entry.claim!r}; "
                f"source may re-promote on next consolidation"
            )
        turn.revoked = True
    if entry in semantic:
        semantic.remove(entry)
    # Post-condition: no promotable source remains for this claim.
    for tid in entry.derived_from:
        if not episodic[tid].revoked:
            raise RollbackNonConvergenceError(
                f"turn {tid!r} still promotable after rollback of {entry.claim!r}"
            )
