# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-against-lossy-rewrite-divergence.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-against-lossy-rewrite-divergence.warrant.json
# Markdown SHA-256:   a8e2461a3043e3d2a06a652d8f219977b82d2c30b803f395f6d21b2598056131
# Code AST SHA-256:   582e88ee039f12f0ca7cd3c1851af07caf0300c87f7a992eaa983cc238e7e85c
# Verified Classes:   SpanClass, Span, RewriteProposal, RewriteDivergenceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class SpanClass(Enum):
    NARRATIVE = "narrative"          # safe to paraphrase
    BRANCH_DETERMINING = "branch"    # must survive verbatim or be pinned
    NEGATIVE_RESULT = "negative"     # must survive verbatim or be pinned


@dataclass
class Span:
    span_id: str
    text: str
    span_class: SpanClass
    pinned_externally: bool = False


@dataclass
class RewriteProposal:
    summarized_span_ids: list[str]
    summary_text: str


class RewriteDivergenceError(RuntimeError):
    """Raised when a self-edit would drop or paraphrase a branch-determining fact
    without verbatim retention or an external pin, making the summary the sole
    carrier of evidence the agent will later treat as observation."""


def gate_self_rewrite(spans: list[Span], proposal: RewriteProposal) -> list[Span]:
    by_id = {s.span_id: s for s in spans}
    surviving: list[Span] = []

    for span_id in proposal.summarized_span_ids:
        span = by_id.get(span_id)
        if span is None:
            raise RewriteDivergenceError(
                f"proposal references unknown span {span_id!r}"
            )

        if span.span_class in (SpanClass.BRANCH_DETERMINING, SpanClass.NEGATIVE_RESULT):
            # Branch-determining and negative-result spans may not be paraphrased
            # away. They must be retained verbatim or pinned to an external store.
            if not span.pinned_externally:
                raise RewriteDivergenceError(
                    f"span {span_id!r} ({span.span_class.value}) would be paraphrased "
                    f"into the summary without verbatim retention or external pin; "
                    f"summary would become the sole carrier of a branch-determining "
                    f"fact. Refuse compaction and escalate."
                )
            # Pinned: safe to drop from window, but record survives externally.
            continue

        # Narrative spans: safe to fold into the summary.
        surviving.append(span)

    # The summary itself is instance-authored testimony, never raw evidence.
    surviving.append(
        Span(
            span_id=f"summary:{proposal.summarized_span_ids[0]}..",
            text=proposal.summary_text,
            span_class=SpanClass.NARRATIVE,
        )
    )
    return surviving


def compact(agent_spans: list[Span], proposal: RewriteProposal) -> list[Span]:
    try:
        return gate_self_rewrite(agent_spans, proposal)
    except RewriteDivergenceError:
        # Do not fall back to a lossy summary. Truncate only non-branching spans
        # or halt for external checkpointing.
        raise
