# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-prune-its-own-working-context-during-self-editing-rewrites.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-prune-its-own-working-context-during-self-editing-rewrites.warrant.json
# Markdown SHA-256:   afcd9a549eac8057afd8b2d8f178aae9e927fc32aae875d6828d3e33e8e4cd04
# Code AST SHA-256:   e00f1b6947ae8d7534fffd254b816c03e60eed11f5148b41ea992ca94acb85a6
# Verified Classes:   ContextPruneViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ContextPruneViolation(RuntimeError):
    """Raised when a self-edit rewrite would delete load-bearing context."""
    pass


PROTECTED_KINDS = frozenset({
    "negative_result",
    "constraint",
    "precondition",
    "provenance_marker",
})


def validate_self_edit(pre_spans, post_spans, open_obligations):
    """
    pre_spans: list of dicts with keys: id, kind, text, discharged_by (or None)
    post_spans: list of dicts retained after the rewrite, plus tombstones with
                keys: id, tombstone (bool), live_referent (or None)
    open_obligations: set of span ids still required by pending plan steps
    """
    retained = {s["id"]: s for s in post_spans}
    tombstones = {s["id"]: s for s in post_spans if s.get("tombstone")}

    for span in pre_spans:
        sid = span["id"]
        if sid in retained:
            continue

        # Span was removed by the rewrite. Is removal justified?
        covered = sid in tombstones or span.get("live_referent") is not None
        discharged = span.get("discharged_by") is not None

        if span["kind"] in PROTECTED_KINDS and not (covered or discharged):
            raise ContextPruneViolation(
                f"rewrite deleted protected span {sid!r} "
                f"(kind={span['kind']!r}) with no tombstone, live referent, "
                f"or discharge record; relevance oracle was plan-relative, "
                f"which cannot see disconfirming evidence"
            )

        if sid in open_obligations:
            raise ContextPruneViolation(
                f"rewrite deleted span {sid!r} still bound to an open "
                f"obligation; post-rewrite context cannot prove step validity"
            )

    # Post-rewrite must still prove every open obligation is satisfiable.
    for ob_id in open_obligations:
        if ob_id not in retained and ob_id not in tombstones:
            raise ContextPruneViolation(
                f"open obligation {ob_id!r} has no retained evidence or "
                f"tombstone after rewrite; context is now unprovable"
            )
    return True
