# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-during-episodic-to-semantic-memory-consolidation-in-persistent-agent-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-during-episodic-to-semantic-memory-consolidation-in-persistent-agent-stores.warrant.json
# Markdown SHA-256:   d8a996e21bea5dad7a291bb1a791966b0438001b2a065f16627c84eba888a8ec
# Code AST SHA-256:   1d659029c65e48a9d30194b4062b29f1b1c664c506136f6e660abf2e2d6cba94
# Verified Classes:   TrustClass, ProvenanceLaunderingError, Episode, SemanticRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class TrustClass(IntEnum):
    UNTRUSTED = 0
    TOOL_OUTPUT = 1
    SUBAGENT = 2
    USER = 3
    TRUSTED = 4


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a semantic record's trust class exceeds its episodic ancestors'
    minimum trust, or when it carries no resolvable episodic ancestor."""


@dataclass
class Episode:
    id: str
    trust: TrustClass
    quarantined: bool = False


@dataclass
class SemanticRecord:
    id: str
    claim: str
    claimed_trust: TrustClass
    derived_from: list[str] = field(default_factory=list)


def admit_semantic_record(
    record: SemanticRecord,
    episode_index: dict[str, Episode],
    allow_quarantined_ancestors: bool = False,
) -> TrustClass:
    """Enforce the dominance invariant before a distilled record enters the store.

    Returns the effective (downgraded) trust class to persist.
    Raises if the record cannot be soundly admitted.
    """
    if not record.derived_from:
        raise ProvenanceLaunderingError(
            f"semantic record {record.id!r} has no episodic ancestor; "
            "free-floating facts cannot be admitted to a trusted tier"
        )

    missing = [eid for eid in record.derived_from if eid not in episode_index]
    if missing:
        raise ProvenanceLaunderingError(
            f"semantic record {record.id!r} references unknown ancestors {missing}"
        )

    ancestors = [episode_index[eid] for eid in record.derived_from]

    if not allow_quarantined_ancestors:
        quarantined = [a.id for a in ancestors if a.quarantined]
        if quarantined:
            raise ProvenanceLaunderingError(
                f"semantic record {record.id!r} derived from quarantined "
                f"episodes {quarantined}; distillation must exclude them"
            )

    floor = min(a.trust for a in ancestors)
    if record.claimed_trust > floor:
        raise ProvenanceLaunderingError(
            f"provenance laundering: record {record.id!r} claims "
            f"{record.claimed_trust.name} but ancestor floor is {floor.name}"
        )

    # Sound: persist at the ancestor floor, never above it.
    return floor
