# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-model-driven-context-rewriting-as-a-destructive-operation-on-its-own-memory-substrate-rather-than-a-compressi.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-model-driven-context-rewriting-as-a-destructive-operation-on-its-own-memory-substrate-rather-than-a-compressi.warrant.json
# Markdown SHA-256:   ed18cb581405a2283cc8e211781b6b0cdaa66c0af0271df330e2bc32049ce3d8
# Code AST SHA-256:   efd84d341ff12341b9eb11179746eafd0dd62acd1b6c252de32a029a2dbfb6fd
# Verified Classes:   UnverifiableSelfEditError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnverifiableSelfEditError(RuntimeError):
    """Raised when a model-driven context rewrite would destroy the sole copy
    of a provenance-bearing commitment, leaving no substrate-independent
    reference for later verification."""
    pass


# Token classes whose exact form is load-bearing for future actions.
BINDING_CLASSES = {"prohibition", "numeric_threshold", "reserved_identifier", "ordering_constraint"}


def authorize_self_edit(span_tokens, rewrite_kind, has_external_checkpoint, verifier_reads_original):
    """
    Decide whether a self-edit may proceed in place, must checkpoint, or must abort.

    span_tokens: list of dicts with keys 'class', 'text'
    rewrite_kind: 'extractive' | 'paraphrase'
    has_external_checkpoint: bool -- verbatim span persisted to append-only store
    verifier_reads_original: bool -- a later check reads the pre-edit original
    """
    binding = [t for t in span_tokens if t["class"] in BINDING_CLASSES]

    if not binding:
        # Provenance-free span: in-place compression is safe.
        return "compress_in_place"

    if not has_external_checkpoint:
        # Binding commitments would survive only as a paraphrase.
        raise UnverifiableSelfEditError(
            f"self-edit would destroy sole copy of {len(binding)} binding "
            f"commitment(s) via {rewrite_kind} rewrite with no external "
            f"checkpoint; post-edit state is unverifiable from the inside"
        )

    if rewrite_kind == "paraphrase" and not verifier_reads_original:
        # Paraphrase can invert polarity; no independent reader to catch it.
        raise UnverifiableSelfEditError(
            "paraphrase rewrite of binding commitments with no "
            "substrate-independent verifier: executor and verifier would "
            "share the corrupted store, guaranteeing false agreement"
        )

    # Checkpoint exists and either extraction-only or independently verified.
    return "checkpoint_then_rewrite"


def run_self_edit(span_tokens, rewrite_kind, has_external_checkpoint, verifier_reads_original):
    decision = authorize_self_edit(
        span_tokens, rewrite_kind, has_external_checkpoint, verifier_reads_original
    )
    if decision == "compress_in_place":
        return {"mode": "in_place", "pointer": None}
    return {"mode": "checkpointed", "pointer": "append_only://span/<id>"}
