# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-model-driven-context-pruning-to-prevent-invariant-erasure-across-checkpoint-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-model-driven-context-pruning-to-prevent-invariant-erasure-across-checkpoint-boundaries.warrant.json
# Markdown SHA-256:   cbb0227c0863c68c0e3b70e2f940fd994da4fea7e6f44e45846450b3c5a3386b
# Code AST SHA-256:   6df16d5b1a1488010958c408810c634d4b12146ffa322f4b14fc42c2d6768211
# Verified Classes:   InvariantErasureError, InvariantRegister
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class InvariantErasureError(RuntimeError):
    """Raised when a pruning/rewrite operation would drop or alter a pinned invariant,
    or when a resumed checkpoint's invariant register does not match its recorded hash."""
    pass


@dataclass
class InvariantRegister:
    # Append-only. The pruner has no write authority here.
    spans: list[str] = field(default_factory=list)

    def pin(self, span: str) -> None:
        self.spans.append(span)

    def digest(self) -> str:
        h = hashlib.sha256()
        for s in self.spans:
            h.update(s.encode("utf-8"))
            h.update(b"\x00")
        return h.hexdigest()


def prune_context(window: list[str], register: InvariantRegister,
                  summarize) -> list[str]:
    """Model-driven prune. Refuses if any pinned invariant span is present in the
    prunable region, because dropping it would erase a load-bearing constraint."""
    pinned = set(register.spans)
    prunable = [w for w in window if w not in pinned]
    protected = [w for w in window if w in pinned]

    # Guard: an invariant that appears in the window must survive verbatim.
    rewritten = summarize(prunable)
    surviving = set(rewritten) | set(protected)

    for span in pinned:
        if span in window and span not in surviving:
            raise InvariantErasureError(
                f"prune would erase pinned invariant: {span!r}"
            )

    return protected + rewritten


def resume(checkpoint_window: list[str], checkpoint_hash: str,
           register: InvariantRegister, summarize) -> list[str]:
    """Resume a checkpointed context. If the register hash drifted, the substrate
    is corrupt and the instance must halt rather than act on a degraded window."""
    if register.digest() != checkpoint_hash:
        raise InvariantErasureError(
            "invariant register hash mismatch on resume; "
            "refusing to act on degraded context"
        )
    return prune_context(checkpoint_window, register, summarize)
