# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-episodic-memory-entry-before-semantic-distillation-promotes-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-episodic-memory-entry-before-semantic-distillation-promotes-it.warrant.json
# Markdown SHA-256:   30a6fd2509448df2634d693bdc5639a664e7c0d08d14717174bf3a7931658df4
# Code AST SHA-256:   4465d63ac91a2e8580ea96f8db2e8fd8303fff15d9248d5a75fcf09020b75b98
# Verified Classes:   PromotionDecision, DistillationGateError, EpisodicEntry, DistillationCluster
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class PromotionDecision(Enum):
    PROMOTE = "promote"
    QUARANTINE = "quarantine"
    REJECT = "reject"


class DistillationGateError(RuntimeError):
    """Raised when the gate cannot make a sound decision from the available metadata."""


@dataclass(frozen=True)
class EpisodicEntry:
    entry_id: str
    content: str
    trust: str            # "trusted" | "untrusted" — write-once, set at ingestion
    source: str
    is_user_turn: bool
    asserts_state_change: bool


@dataclass
class DistillationCluster:
    novel_claim: str
    contributing: list[EpisodicEntry] = field(default_factory=list)


IMPERATIVE_MARKERS = ("note for the assistant", "update all references", "you must", "ignore previous")


def _has_agent_imperative(entry: EpisodicEntry) -> bool:
    if entry.is_user_turn:
        return False  # user turns may legitimately instruct
    low = entry.content.lower()
    return any(m in low for m in IMPERATIVE_MARKERS)


def _carries_novel_claim(entry: EpisodicEntry, claim: str) -> bool:
    # Simplified: the novel value (e.g. a hostname) appears in this entry.
    return claim.split()[-1].lower() in entry.content.lower()


def gate(cluster: DistillationCluster) -> PromotionDecision:
    if not cluster.contributing:
        raise DistillationGateError(
            f"cluster for claim {cluster.novel_claim!r} has no contributing entries; "
            "cannot evaluate trust asymmetry — refusing to promote"
        )

    if any(e.trust not in ("trusted", "untrusted") for e in cluster.contributing):
        raise DistillationGateError(
            "contributing entry has unknown trust value; provenance invariant violated"
        )

    # Signal 1: agent-directed imperative in a non-user-turn artifact -> hard reject.
    for e in cluster.contributing:
        if _has_agent_imperative(e):
            return PromotionDecision.REJECT

    claim_sources = [e for e in cluster.contributing if _carries_novel_claim(e, cluster.novel_claim)]
    trusted_sources = [e for e in claim_sources if e.trust == "trusted"]
    untrusted_sources = [e for e in claim_sources if e.trust == "untrusted"]

    # Signal 2: consensus carried solely by lowest-trust member.
    if untrusted_sources and not trusted_sources:
        return PromotionDecision.QUARANTINE

    # Signal 3: single-source novelty.
    if len(claim_sources) < 2 and untrusted_sources:
        return PromotionDecision.QUARANTINE

    # Signal 4: single-source state-change claim with no temporal corroboration.
    if any(e.asserts_state_change for e in claim_sources) and len(claim_sources) < 2:
        return PromotionDecision.QUARANTINE

    if trusted_sources and all(e.trust == "trusted" for e in cluster.contributing):
        return PromotionDecision.PROMOTE

    # Mixed cluster with corroboration: promote only if trusted corroboration exists.
    if len(trusted_sources) >= 2:
        return PromotionDecision.PROMOTE

    return PromotionDecision.QUARANTINE


def enforce(cluster: DistillationCluster) -> PromotionDecision:
    decision = gate(cluster)
    if decision is PromotionDecision.PROMOTE and not cluster.contributing:
        raise DistillationGateError("promotion path reached with empty contributing set")
    return decision
