# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-model-driven-context-compaction-when-the-summarizer-s-own-output-is-the-evidence-it-is-summarizing.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-model-driven-context-compaction-when-the-summarizer-s-own-output-is-the-evidence-it-is-summarizing.warrant.json
# Markdown SHA-256:   1d26907b3af247721943d9949832198bc95e71950ef85af709ccfc0fecb90b52
# Code AST SHA-256:   c2c94f3c38c11f8ef63100a70e8c9b969b7cbe82f6869fc8b8af894c67a2be5f
# Verified Classes:   UnverifiableCompactionError, Span, ContextStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnverifiableCompactionError(RuntimeError):
    """Raised when a compaction pass would summarize a prior self-summary
    whose original span is no longer retrievable."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    is_derivative: bool = False          # produced by a prior compaction
    provenance: Optional[str] = None     # e.g. "compact:v3,src=turns_1-22"
    original_ref: Optional[str] = None   # pointer into immutable store, if any
    decision_bearing: bool = False       # contains numbers/commitments/causal claims


@dataclass
class ContextStore:
    spans: list = field(default_factory=list)
    immutable: dict = field(default_factory=dict)   # span_id -> original bytes

    def recall(self, span_id: str) -> str:
        if span_id not in self.immutable:
            raise UnverifiableCompactionError(
                f"no immutable original for {span_id}; cannot verify derivative"
            )
        return self.immutable[span_id]


def compact(store: ContextStore, target: Span, summary_text: str, depth: int) -> Span:
    """Compact a span into a summary, enforcing the depth<=1 invariant."""
    # C1: is this a derivative we produced ourselves?
    if target.is_derivative:
        # C2: is the original still addressable?
        if target.original_ref is None or target.original_ref not in store.immutable:
            # C3: does it carry decision-bearing content?
            if target.decision_bearing:
                raise UnverifiableCompactionError(
                    f"refusing depth-{depth} compaction of derivative span "
                    f"{target.span_id!r} (provenance={target.provenance!r}): "
                    f"original unrecoverable and region is decision-bearing. "
                    f"Evict + require recall() instead."
                )
        # depth cap over unrecoverable originals
        if depth > 1 and target.original_ref is None:
            raise UnverifiableCompactionError(
                f"compaction depth {depth} exceeds cap 1 over unrecoverable "
                f"original {target.span_id!r}"
            )

    new = Span(
        span_id=f"{target.span_id}.c{depth}",
        text=summary_text,
        is_derivative=True,
        provenance=f"compact:v{depth},src={target.span_id}",
        original_ref=target.original_ref or target.span_id,
        decision_bearing=target.decision_bearing,
    )
    return new


def evict(store: ContextStore, target: Span) -> Span:
    """Safe alternative: drop the span, keep an addressable pointer."""
    if target.span_id not in store.immutable and not target.is_derivative:
        store.immutable[target.span_id] = target.text
    return Span(
        span_id=f"{target.span_id}.ptr",
        text=f"⟨evicted:{target.span_id}; call recall({target.span_id!r})⟩",
        is_derivative=False,
        original_ref=target.span_id,
        decision_bearing=target.decision_bearing,
    )
