# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-self-editing-context-compression-as-a-non-idempotent-state-mutation-rather-than-a-lossy-read.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-self-editing-context-compression-as-a-non-idempotent-state-mutation-rather-than-a-lossy-read.warrant.json
# Markdown SHA-256:   5c6ccf40cf0172e83aed7268c6d3ed97bae8805a1f3c60fffe85fb85beefff09
# Code AST SHA-256:   b3babd47078d059fc0f6dfef08d11286a7d486edc401ae9e06573b34874b3177
# Verified Classes:   CompressionInvariantViolation, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CompressionInvariantViolation(RuntimeError):
    """Raised when a self-edit would destroy un-externalized commitments
    or would feed a prior summary back into its own compressor."""
    pass


class Span:
    def __init__(self, span_id: str, text: str, is_summary: bool = False):
        self.span_id = span_id
        self.text = text
        self.is_summary = is_summary


def self_edit_compress(
    buffer: list[Span],
    obligations: set[str],
    external_store_has: set[str],
    budget_tokens: int,
    current_tokens: int,
) -> list[Span]:
    """Compress the working buffer under budget pressure.

    Invariants enforced:
      1. Compression may not consume its own prior output (no summary-of-summary
         unless the summary is re-externalized first).
      2. Compression may not run while any obligation is un-pinned / implicit.
      3. If the buffer is the only copy of a span, auto-compression is refused.
    """
    if current_tokens <= budget_tokens:
        return buffer

    # Invariant 2: obligations must be externalized before any destructive edit.
    implicit_obligations = obligations - external_store_has
    if implicit_obligations:
        raise CompressionInvariantViolation(
            f"refusing self-edit: {len(implicit_obligations)} obligation(s) "
            f"exist only in-buffer and would be destroyed: "
            f"{sorted(implicit_obligations)[:5]}"
        )

    # Invariant 1: a prior summary must not be re-compressed in place.
    prior_summaries = [s for s in buffer if s.is_summary]
    if prior_summaries:
        raise CompressionInvariantViolation(
            f"refusing self-edit: buffer contains {len(prior_summaries)} prior "
            f"summary span(s) that would be summarized again; re-externalize "
            f"and re-fetch by reference instead of compressing the summary."
        )

    # Invariant 3: every span must be recoverable from the external store.
    unrecoverable = [s.span_id for s in buffer if s.span_id not in external_store_has]
    if unrecoverable:
        raise CompressionInvariantViolation(
            f"refusing self-edit: buffer is sole copy of {len(unrecoverable)} "
            f"span(s) {unrecoverable[:5]}; checkpoint to external store first."
        )

    # Safe path: lossy read semantics. Evict oldest, record eviction map,
    # leave obligations pinned and untouched.
    keep = buffer[len(buffer) // 2:]
    summary = Span(
        span_id="summary-1",
        text="<generated summary of evicted spans; obligations pinned externally>",
        is_summary=True,
    )
    return [summary] + keep
