# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-model-driven-context-rewriting-as-a-lossy-transaction-rather-than-an-idempotent-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-model-driven-context-rewriting-as-a-lossy-transaction-rather-than-an-idempotent-compaction.warrant.json
# Markdown SHA-256:   28a991bb5370bbfee582bd7f12db8e08f4a7747b0bd30d2bcf26bb8bef148ac5
# Code AST SHA-256:   0590c897600bb7798f6ba6095e5062d3e7c843bcac03a1baf52c441adf1cd7be
# Verified Classes:   UnsafeSelfEdit, ContextSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnsafeSelfEdit(RuntimeError):
    """Raised when a model-driven context rewrite would destroy the sole evidence
    for an open obligation (unverified claim, pending edit, live literal)."""
    pass


class ContextSpan:
    def __init__(self, span_id, text, rewrite_depth=0):
        self.span_id = span_id
        self.text = text
        self.rewrite_depth = rewrite_depth


def safe_self_edit(span, open_obligations, extracted_store, max_depth=1):
    """
    Permit a lossy model rewrite only if:
      - no open obligation references a literal that lives solely in this span,
      - the span has not already been model-rewritten past max_depth,
      - every live literal has been extracted verbatim into extracted_store first.
    """
    # 1. Depth guard: compounding paraphrase loss.
    if span.rewrite_depth >= max_depth:
        raise UnsafeSelfEdit(
            f"span {span.span_id} already rewritten {span.rewrite_depth}x; "
            f"further lossy rewrite would compound paraphrase drift"
        )

    # 2. Pin guard: is this span the sole evidence for a live literal?
    live_literals = {
        lit for ob in open_obligations
        for lit in ob.required_literals
    }
    for lit in live_literals:
        in_span = lit in span.text
        in_store = lit in extracted_store
        if in_span and not in_store:
            raise UnsafeSelfEdit(
                f"span {span.span_id} is sole evidence for literal {lit!r} "
                f"required by open obligation; extract verbatim before rewrite"
            )

    # 3. Unverified-claim guard: never compact mid-verification.
    for ob in open_obligations:
        if ob.state == "claimed_unverified" and ob.evidence_span == span.span_id:
            raise UnsafeSelfEdit(
                f"span {span.span_id} holds unverified claim {ob.id}; "
                f"compaction would strip the evidence needed to detect silent failure"
            )

    # Safe: extract literals, then rewrite narrative.
    for lit in live_literals:
        if lit in span.text:
            extracted_store[lit] = span.text  # verbatim pre-image retained
    return ContextSpan(
        span_id=span.span_id,
        text=rewrite_narrative(span.text),
        rewrite_depth=span.rewrite_depth + 1,
    )


def rewrite_narrative(text):
    # Model-driven paraphrase; non-deterministic, non-replayable.
    return text  # placeholder for the model call
