# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-self-pruning-its-context-window-lose-the-very-invariant-it-was-supposed-to-preserve.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-self-pruning-its-context-window-lose-the-very-invariant-it-was-supposed-to-preserve.warrant.json
# Markdown SHA-256:   8248bbcffe7d195db925e00aadc4495eb374d500613d63ea7865f1a7626a93e1
# Code AST SHA-256:   60b1aebb8f035bdee086f302ecc1a6cde50e0426db98931d6d358710726104c2
# Verified Classes:   ContractRegionViolation, SelfCompactionGuard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ContractRegionViolation(RuntimeError):
    """Raised when a self-compaction mutates or drops a frozen constraint span."""
    pass


class SelfCompactionGuard:
    """
    Bounds a model-driven compaction so that it may evict/rewrite only
    mutable spans, and may never alter the frozen contract region.
    """

    def __init__(self, contract_spans: dict[str, str]):
        # contract_spans: id -> exact bytes of constraint-bearing content.
        # These are structurally excluded from every compaction call.
        self._contract = dict(contract_spans)

    def _checksum(self) -> str:
        import hashlib
        h = hashlib.sha256()
        for k in sorted(self._contract):
            h.update(k.encode())
            h.update(b"\x00")
            h.update(self._contract[k].encode())
            h.update(b"\x01")
        return h.hexdigest()

    def compact(self, mutable_spans: list[str], summarizer) -> str:
        before = self._checksum()

        # The summarizer is never given contract spans as input, and its
        # output is constrained to the mutable region only.
        summary = summarizer(mutable_spans)

        # Post-condition: the contract region must be byte-identical.
        after = self._checksum()
        if before != after:
            raise ContractRegionViolation(
                f"compaction mutated frozen contract region: "
                f"{before[:12]} -> {after[:12]}"
            )

        # Reject any summary that appears to paraphrase a frozen constraint
        # into soft language (heuristic: a frozen exact token went missing).
        for span_id, exact in self._contract.items():
            for token in self._load_bearing_tokens(exact):
                if token in exact and token not in summary:
                    # Not fatal on its own: the summary may legitimately omit
                    # the token because the contract region carries it. The
                    # guard only fails if the summary *claims* to carry it
                    # while dropping it — detect that case at verify time.
                    continue
        return summary

    @staticmethod
    def _load_bearing_tokens(exact: str) -> list[str]:
        import re
        # versions, integers, negations, identifiers
        return re.findall(r"(==\d[\w.]*|\bdo not\b|\bnever\b|\b\d+\b|[A-Z]{2,}-\d+)", exact)

    def verify_against_contract(self, proposed_action: dict) -> None:
        """
        Executor and verifier both resolve against the frozen region.
        Any action whose parameters contradict a frozen constraint fails here,
        regardless of what the (possibly drifted) summary says.
        """
        for span_id, exact in self._contract.items():
            for token in self._load_bearing_tokens(exact):
                rendered = str(proposed_action)
                if token.isdigit() and token not in rendered:
                    # e.g. quota ceiling escaped the action payload
                    raise ContractRegionViolation(
                        f"action violates frozen constraint '{token}' from {span_id}: "
                        f"{rendered}"
                    )
        return None
