# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-self-editing-context-pass-as-a-state-mutating-commit-rather-than-a-lossless-cache-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-self-editing-context-pass-as-a-state-mutating-commit-rather-than-a-lossless-cache-eviction.warrant.json
# Markdown SHA-256:   1156f58e631cc396f7e5664b1695e7916398d75d258bab436240c270d08b296a
# Code AST SHA-256:   00fbbc780c8e1505846c59f9f091090e58595a2483169acb490f4f003f4d7d66
# Verified Classes:   SelfEditViolation, SpanKind, Span, SelfEditPass
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class SelfEditViolation(RuntimeError):
    """Raised when a context-rewrite pass would drop non-reconstructible or constraint-bearing state."""
    pass


class SpanKind(Enum):
    USER_CONSTRAINT = "user_constraint"
    NEGATIVE_CONSTRAINT = "negative_constraint"
    ONE_SHOT_TOOL_OUTPUT = "one_shot_tool_output"
    SAMPLED_REASONING = "sampled_reasoning"
    RECONSTRUCTIBLE = "reconstructible"


PINNED_KINDS = {
    SpanKind.USER_CONSTRAINT,
    SpanKind.NEGATIVE_CONSTRAINT,
    SpanKind.ONE_SHOT_TOOL_OUTPUT,
    SpanKind.SAMPLED_REASONING,
}


@dataclass
class Span:
    span_id: str
    kind: SpanKind
    relevance: float
    rederive_tool: str | None = None


@dataclass
class SelfEditPass:
    pinned: dict[str, Span] = field(default_factory=dict)
    evicted: dict[str, Span] = field(default_factory=dict)

    def apply(self, spans: list[Span], evict_below: float) -> None:
        for s in spans:
            if s.relevance >= evict_below:
                continue
            if s.kind in PINNED_KINDS:
                # Never let a relevance score delete constraint-bearing or
                # non-reconstructible state. Pin it verbatim instead.
                if s.span_id in self.evicted:
                    raise SelfEditViolation(
                        f"span {s.span_id} ({s.kind.value}) was previously evicted "
                        f"and now must be pinned; state already lost this episode"
                    )
                self.pinned[s.span_id] = s
                continue
            if s.kind is SpanKind.RECONSTRUCTIBLE and s.rederive_tool:
                self.evicted[s.span_id] = s  # safe: re-derivable via named tool
                continue
            raise SelfEditViolation(
                f"span {s.span_id} kind={s.kind.value} has no rederive_tool "
                f"and is not pinnable; eviction would be an unrecoverable commit"
            )

    def assert_destructive_action_ok(self, action: str, cited_ids: set[str]) -> None:
        required = {sid for sid, s in self.pinned.items()
                    if s.kind in {SpanKind.USER_CONSTRAINT, SpanKind.NEGATIVE_CONSTRAINT}}
        missing = required - cited_ids
        if missing:
            raise SelfEditViolation(
                f"destructive action {action!r} did not cite pinned constraints {sorted(missing)}"
            )


if __name__ == "__main__":
    p = SelfEditPass()
    # The turn-2 constraint, low relevance to the current subgoal, is the trap.
    spans = [
        Span("turn2_legacy_id", SpanKind.USER_CONSTRAINT, relevance=0.11),
        Span("turn5_schema_dump", SpanKind.RECONSTRUCTIBLE, relevance=0.12,
             rederive_tool="read_file:orders.sql"),
    ]
    p.apply(spans, evict_below=0.30)  # pins turn2_legacy_id, evicts the dump
    p.assert_destructive_action_ok("DROP COLUMN legacy_id", cited_ids=set())  # raises
