# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-pruned-spans-when-self-editing-context-policies-are-scored-against-the-post-edit-window.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-pruned-spans-when-self-editing-context-policies-are-scored-against-the-post-edit-window.warrant.json
# Markdown SHA-256:   afaba5fbdba7e4caa101852d306097780f9b794e18e4864d0f090caebd67d697
# Code AST SHA-256:   37ef0e67f14b5b6b212fffae4179c4ea8e052af0bcece95961fd92c1f8f04ac6
# Verified Classes:   ResurrectionInvariantError, Span, SelfEditingContext
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ResurrectionInvariantError(RuntimeError):
    """Raised when a pruned span's descendant re-enters the retention candidate set."""
    pass


class Span:
    def __init__(self, span_id: str, tokens: int, derived_from: str | None = None):
        self.span_id = span_id
        self.tokens = tokens
        self.derived_from = derived_from  # None for primary evidence
        self.pruned = False


class SelfEditingContext:
    def __init__(self, max_tokens: int):
        self.max_tokens = max_tokens
        self.window: dict[str, Span] = {}
        self.pruned: set[str] = set()
        self.derived_budget = int(max_tokens * 0.15)

    def prune(self, span_id: str, rewrite: Span) -> None:
        if span_id not in self.window:
            raise ResurrectionInvariantError(f"prune target {span_id} not in window")
        self.pruned.add(span_id)
        del self.window[span_id]
        rewrite.derived_from = span_id
        self.window[rewrite.span_id] = rewrite

    def score_candidates(self) -> list[str]:
        # Candidate set for relevance scoring must exclude derived spans.
        return [sid for sid, s in self.window.items() if s.derived_from is None]

    def retrieve(self, rewrite_id: str) -> Span:
        rw = self.window.get(rewrite_id)
        if rw is None or rw.derived_from is None:
            raise ResurrectionInvariantError(f"{rewrite_id} is not a derived span")
        origin = rw.derived_from
        if origin in self.pruned:
            # Traversing rewrite -> original is forbidden; it is the resurrection pump.
            raise ResurrectionInvariantError(
                f"retrieval of {rewrite_id} would resurrect pruned span {origin}"
            )
        return self.window[origin]

    def enforce(self) -> None:
        for sid in self.window:
            if sid in self.pruned:
                raise ResurrectionInvariantError(f"pruned span {sid} present in window")
        derived = sum(s.tokens for s in self.window.values() if s.derived_from)
        if derived > self.derived_budget:
            raise ResurrectionInvariantError(
                f"derived-span budget exceeded: {derived} > {self.derived_budget}"
            )
