# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-episodic-to-semantic-promotion-when-scratchpad-residue-contaminates-the-distillation-window.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-episodic-to-semantic-promotion-when-scratchpad-residue-contaminates-the-distillation-window.warrant.json
# Markdown SHA-256:   f5b3085dccab55cf5031cbf414ca21d9953876640ff0994c2dedf0504395bdb8
# Code AST SHA-256:   ac03f8ea0463a719601b69802260e3ce67f5d1ebf47700cfc5f09476feef2b89
# Verified Classes:   Provenance, Span, PromotionRefused
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Iterable

class Provenance(Enum):
    OBSERVED = "observed"
    DERIVED = "derived"
    SPECULATIVE = "speculative"

@dataclass(frozen=True)
class Span:
    span_id: str
    text: str
    provenance: Provenance
    corrects: str | None = None  # span_id this span supersedes

class PromotionRefused(RuntimeError):
    """Raised when distillation would promote unsourced or orphaned-correction residue."""

def distill_to_semantic(window: Iterable[Span], candidate_claim: str) -> Span:
    spans = list(window)
    by_id = {s.span_id: s for s in spans}
    superseded = {s.corrects for s in spans if s.corrects}

    # Guard 1: orphaned corrections — a correction whose target was evicted.
    for s in spans:
        if s.corrects and s.corrects not in by_id:
            raise PromotionRefused(
                f"correction {s.span_id} targets evicted span {s.corrects}; "
                f"window is incomplete, refusing promotion"
            )

    # Guard 2: any speculative span not superseded by a later correction
    # poisons every claim entailed by it.
    unsuperseded_spec = [
        s for s in spans
        if s.provenance is Provenance.SPECULATIVE and s.span_id not in superseded
    ]
    if unsuperseded_spec:
        raise PromotionRefused(
            f"candidate claim '{candidate_claim[:40]}...' entailed by "
            f"unsuperseded speculative span(s) "
            f"{[s.span_id for s in unsuperseded_spec]}; refusing promotion"
        )

    # Guard 3: claim must trace to at least one observed span.
    observed = [s for s in spans if s.provenance is Provenance.OBSERVED]
    if not observed:
        raise PromotionRefused(
            f"no observed span in window backs '{candidate_claim[:40]}...'; "
            f"downgrade to derived, do not admit to belief tier"
        )

    return Span(
        span_id=f"sem:{observed[0].span_id}",
        text=candidate_claim,
        provenance=Provenance.OBSERVED,
    )
