# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-in-place-summarization-collapse-and-the-provenance-anchor-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-in-place-summarization-collapse-and-the-provenance-anchor-invariant.warrant.json
# Markdown SHA-256:   b00ee57248719c2ca546fef4ddf44fd80ebb55483a2aa7c6aa77c20a9c6e97d3
# Code AST SHA-256:   d6b2e2d19cce29a5a83427acd904b580b749892a0ab4d158ca07797618e84fee
# Verified Classes:   ContextRewriteError, SpanClass, Span, RewritePlan
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ContextRewriteError(RuntimeError):
    """Raised when an in-place context rewrite would destroy unrecoverable state."""
    pass


class SpanClass(Enum):
    CHATTER = "chatter"            # safe to elide
    RESOLVED = "resolved"          # elidable only if no downstream dependency
    CONSTRAINT = "constraint"      # never elidable
    NEGATIVE_RESULT = "negative"   # never elidable ("we tried X, it failed")
    DECISION = "decision"          # elidable only with a source pointer


@dataclass
class Span:
    span_id: str
    cls: SpanClass
    text: str
    source_ref: Optional[str] = None   # pointer into immutable store


@dataclass
class RewritePlan:
    elide: list[str] = field(default_factory=list)
    summarize: list[str] = field(default_factory=list)
    depth: int = 1                     # generations from immutable source


MAX_REWRITE_DEPTH = 1


def validate_rewrite(spans: dict[str, Span], plan: RewritePlan,
                     backing_store_available: bool) -> None:
    if not backing_store_available:
        raise ContextRewriteError(
            "in-place rewrite with no immutable backing store: "
            "pruned spans become unrecoverable and drift is undetectable"
        )

    if plan.depth > MAX_REWRITE_DEPTH:
        raise ContextRewriteError(
            f"rewrite depth {plan.depth} exceeds cap {MAX_REWRITE_DEPTH}: "
            "provenance chain outruns its source; re-derive from store instead"
        )

    for sid in plan.elide:
        span = spans.get(sid)
        if span is None:
            raise ContextRewriteError(f"elide target {sid!r} not found")
        if span.cls in (SpanClass.CONSTRAINT, SpanClass.NEGATIVE_RESULT):
            raise ContextRewriteError(
                f"refusing to elide {span.cls.value} span {sid!r}: "
                "constraints and negative results are non-prunable"
            )
        if span.cls == SpanClass.DECISION and not span.source_ref:
            raise ContextRewriteError(
                f"decision span {sid!r} has no source pointer; "
                "an orphaned decision cannot justify itself after rewrite"
            )

    for sid in plan.summarize:
        span = spans.get(sid)
        if span is None:
            raise ContextRewriteError(f"summarize target {sid!r} not found")
        if span.cls == SpanClass.DECISION and not span.source_ref:
            raise ContextRewriteError(
                f"cannot summarize decision {sid!r} without a source pointer: "
                "the reason for the decision would be lost on next compaction"
            )


def compact_and_continue(spans: dict[str, Span], plan: RewritePlan,
                         backing_store_available: bool) -> dict[str, Span]:
    validate_rewrite(spans, plan, backing_store_available)
    surviving = {sid: s for sid, s in spans.items() if sid not in plan.elide}
    # Summarized spans are replaced by pointer-bearing stubs, never by bare prose.
    for sid in plan.summarize:
        surviving[sid] = Span(
            span_id=sid,
            cls=SpanClass.DECISION,
            text="<summary: see source_ref>",
            source_ref=spans[sid].source_ref or f"store://{sid}",
        )
    return surviving
