# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-model-driven-context-rewrite-as-a-destructive-commit-rather-than-a-compaction-and-how-does-that-distinction.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-model-driven-context-rewrite-as-a-destructive-commit-rather-than-a-compaction-and-how-does-that-distinction.warrant.json
# Markdown SHA-256:   8bb1e200c4e31fdd5f5f9f1e7438d52bafa941db421c0f9da1c215605cf2d73f
# Code AST SHA-256:   53edb67eca2f1f7184e35dfc781dcfd155b9191b3533a75029afa9dad05cb2f1
# Verified Classes:   DestructiveRewriteError, Obligation, ContextSpan, SelfEditGuard
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class DestructiveRewriteError(RuntimeError):
    """Raised when a model-driven context prune would remove the last
    witness for a proposition referenced by a live obligation."""


@dataclass
class Obligation:
    name: str
    required_propositions: set  # proposition ids this obligation depends on


@dataclass
class ContextSpan:
    span_id: str
    text: str
    proposition_ids: set = field(default_factory=set)


class SelfEditGuard:
    def __init__(self, spans: list, obligations: list):
        self.spans = {s.span_id: s for s in spans}
        self.obligations = obligations

    def _witness_count(self, prop_id: str, exclude: set) -> int:
        return sum(
            1
            for sid, span in self.spans.items()
            if sid not in exclude and prop_id in span.proposition_ids
        )

    def commit_prune(self, prune_ids: set, tombstones: dict) -> list:
        """prune_ids: spans the model wants to drop.
        tombstones: prop_id -> preserved-polarity note, for anything the
        model claims it summarized. Returns tombstone records to append.
        """
        new_records = []
        for obl in self.obligations:
            for prop in obl.required_propositions:
                if self._witness_count(prop, exclude=prune_ids) > 0:
                    continue  # still witnessed elsewhere: compaction is safe
                # last witness is inside the prune set -> destructive commit
                if prop not in tombstones:
                    raise DestructiveRewriteError(
                        f"prune of {sorted(prune_ids)} removes sole witness for "
                        f"'{prop}' required by live obligation '{obl.name}' "
                        f"and no polarity-preserving tombstone was supplied"
                    )
                new_records.append(
                    {
                        "prop": prop,
                        "tombstone": tombstones[prop],
                        "digest": hashlib.sha256(
                            tombstones[prop].encode()
                        ).hexdigest()[:16],
                    }
                )
        for sid in prune_ids:
            self.spans.pop(sid, None)
        return new_records


def apply_self_edit(guard: SelfEditGuard, prune_ids: set, tombstones: dict):
    records = guard.commit_prune(prune_ids, tombstones)
    # tombstones are now part of authoritative state; the next tool call
    # must re-verify dependent obligations against them before executing.
    return records


# --- reproduction of the observed failure ---
spans = [
    ContextSpan("s9", "Do NOT rotate primary DB creds; migration in flight",
                {"C1"}),
    ContextSpan("s31", "migration progress notes", {"M1"}),
]
obligations = [Obligation("ensure_credentials_current", {"C1"})]
guard = SelfEditGuard(spans, obligations)

# Model proposes pruning s9 and "summarizing" it without preserving polarity.
try:
    apply_self_edit(guard, prune_ids={"s9"}, tombstones={})
except DestructiveRewriteError as e:
    print("BLOCKED:", e)

# Correct path: tombstone preserves the negation.
recs = apply_self_edit(
    guard,
    prune_ids={"s9"},
    tombstones={"C1": "constraint: do not rotate primary DB creds"},
)
print("COMMITTED with tombstone:", recs)
