# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-the-provenance-of-a-fact-when-it-rewrites-its-own-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-the-provenance-of-a-fact-when-it-rewrites-its-own-context-window.warrant.json
# Markdown SHA-256:   79c5325b78de894d830c8e7114ef15937bc5d2f5daada81799f7df2b5927976c
# Code AST SHA-256:   dd3e309c1edd2d5e84f5bfc055371b8bd195ecaeda754fbcb0171f1557b45574
# Verified Classes:   ProvenanceClass, ProvenanceLaunderingError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ProvenanceClass(Enum):
    RETRIEVED = "retrieved"
    TOOL_ASSERTED = "tool_asserted"
    INFERRED = "inferred"


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a self-edit would collapse a claim's provenance class."""


@dataclass(frozen=True)
class Span:
    text: str
    provenance: ProvenanceClass
    source_ref: str | None
    gates_side_effect: bool


def rewrite_span(span: Span, compressed_text: str, emit_tombstone: bool) -> Span:
    # In-place summarization of a side-effect-gating span is forbidden:
    # it would upgrade a retrieved claim to an unmarked assertion.
    if span.gates_side_effect and not emit_tombstone:
        raise ProvenanceLaunderingError(
            f"refusing in-place summary of side-effect-gating span "
            f"from {span.source_ref!r}; emit a dereferenceable tombstone instead"
        )

    if emit_tombstone:
        if span.source_ref is None:
            raise ProvenanceLaunderingError(
                "cannot emit tombstone for span with no source_ref; "
                "re-fetch required before compression"
            )
        return Span(
            text=f"ref:{span.source_ref}",
            provenance=span.provenance,  # class preserved, not upgraded
            source_ref=span.source_ref,
            gates_side_effect=span.gates_side_effect,
        )

    # Non-gating span: compression admissible, but provenance must survive.
    return Span(
        text=compressed_text,
        provenance=span.provenance,
        source_ref=span.source_ref,
        gates_side_effect=False,
    )


def resume_from_rewrite(span: Span) -> Span:
    # A tombstone must be dereferenced before any downstream side effect.
    if span.gates_side_effect and span.text.startswith("ref:"):
        raise ProvenanceLaunderingError(
            f"tombstone {span.text!r} dereferenced without re-fetch; "
            "freshness (fetched_at) cannot be re-established from a pointer alone"
        )
    return span
