# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-self-rewrite-of-its-own-context-before-eviction-destroys-the-evidence-a-later-step-needs-to-verify-it.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-self-rewrite-of-its-own-context-before-eviction-destroys-the-evidence-a-later-step-needs-to-verify-it.warrant.json
# Markdown SHA-256:   5edf8d4b835d81e47ec26ce451e664624f010a4c8ce87068f2b0ed0fef4ff521
# Code AST SHA-256:   1ccdd17ed2168cb2ed0e427bdee5523607e0a22c0d89657197622f40e2fa02f3
# Verified Classes:   ContextEvictionViolation, SpanKind, Span, ContextWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class ContextEvictionViolation(RuntimeError):
    """Raised when a self-rewrite would evict a span whose exact values a
    downstream step is contracted to verify, without leaving a re-derivable
    pointer to the original."""
    pass


class SpanKind(Enum):
    OBSERVED = "observed"        # tool result, signed assertion, literal
    DERIVED = "derived"          # model paraphrase / summary
    REASONING = "reasoning"      # scratchpad, no verification obligation


@dataclass
class Span:
    turn_id: int
    kind: SpanKind
    text: str
    pointer: str | None = None   # stable handle to the lossless original


@dataclass
class ContextWindow:
    spans: list[Span] = field(default_factory=list)
    utilization: float = 0.0
    pointer_store: dict[str, str] = field(default_factory=dict)

    def _verification_obligated(self, span: Span) -> bool:
        # Observed spans carrying literals/assertions may be re-checked later.
        return span.kind is SpanKind.OBSERVED

    def compact(self, candidate: list[Span], summary_text: str) -> Span:
        """Model-driven rewrite of `candidate` into one summary span.
        Must either retain pointers or fail closed."""
        for span in candidate:
            if self._verification_obligated(span):
                if span.pointer is None:
                    # No handle to the original: eviction would destroy evidence.
                    raise ContextEvictionViolation(
                        f"turn {span.turn_id}: observed span has no re-derivable "
                        f"pointer; refusing lossy self-eviction"
                    )
                if span.pointer not in self.pointer_store:
                    raise ContextEvictionViolation(
                        f"turn {span.turn_id}: pointer {span.pointer!r} not in "
                        f"store; summary would become sole authority"
                    )
        # Safe: emit a DERIVED summary that carries the surviving pointers.
        carried = tuple(s.pointer for s in candidate if s.pointer)
        summary = Span(
            turn_id=candidate[0].turn_id,
            kind=SpanKind.DERIVED,
            text=summary_text,
            pointer=None,
        )
        self.spans = [s for s in self.spans if s not in candidate] + [summary]
        self._carried = carried  # verifier must re-fetch before asserting
        return summary

    def verify_against(self, pointer: str, claimed_value: str) -> bool:
        """A downstream verifier MUST re-derive from the store, never from a
        DERIVED summary."""
        original = self.pointer_store.get(pointer)
        if original is None:
            raise ContextEvictionViolation(
                f"cannot verify {claimed_value!r}: pointer {pointer!r} unreachable"
            )
        return original == claimed_value
