# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-the-self-edit-idempotence-failure-under-mid-execution-token-budgets.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-the-self-edit-idempotence-failure-under-mid-execution-token-budgets.warrant.json
# Markdown SHA-256:   b3c757254f533513ef8aecc8195d1d3c9ab940fe66d90ac609611e467623cc2c
# Code AST SHA-256:   98b6ca8cb32789693cd0e619712314c823065f5e79959c19707ff3916eb5a302
# Verified Classes:   SelfEditInvariantViolation, Obligation, ObligationLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SelfEditInvariantViolation(RuntimeError):
    """Raised when a model-driven prune/rewrite would drop an open obligation."""
    pass


@dataclass
class Obligation:
    oid: str
    kind: str            # "pending_tool" | "constraint" | "checkpoint" | "invariant"
    canonical_span: str  # exact bytes that must survive verbatim
    discharged: bool = False


@dataclass
class ObligationLedger:
    entries: dict[str, Obligation] = field(default_factory=dict)

    def open_obligations(self):
        return [o for o in self.entries.values() if not o.discharged]


def apply_self_edit(
    context: str,
    editable_region: tuple[int, int],
    rewrite_fn,                      # model-driven summarizer
    ledger: ObligationLedger,
    already_edited: set[str],
) -> str:
    start, end = editable_region
    region = context[start:end]

    # Refuse non-idempotent re-edit of an already-summarized span.
    region_key = f"{start}:{end}:{len(region)}"
    if region_key in already_edited:
        raise SelfEditInvariantViolation(
            f"re-edit of already-summarized region {region_key} without raw re-derivation"
        )

    # Any open obligation whose antecedent lies inside the editable region blocks the edit.
    for ob in ledger.open_obligations():
        if ob.canonical_span in region:
            raise SelfEditInvariantViolation(
                f"open obligation {ob.oid} ({ob.kind}) lies inside editable region; "
                f"refuse to prune, spill to external memory or halt"
            )

    rewritten = rewrite_fn(region)

    # Deterministic post-check: every open obligation must remain verbatim-resolvable.
    for ob in ledger.open_obligations():
        if ob.canonical_span not in rewritten and ob.canonical_span not in context[:start] + context[end:]:
            raise SelfEditInvariantViolation(
                f"post-check failed: obligation {ob.oid} unresolvable after rewrite"
            )

    already_edited.add(region_key)
    return context[:start] + rewritten + context[end:]
