# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-lossy-self-rewrite-when-a-model-authored-context-compaction-silently-drops-a-live-constraint-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-lossy-self-rewrite-when-a-model-authored-context-compaction-silently-drops-a-live-constraint-mid-task.warrant.json
# Markdown SHA-256:   316d6e25c36a6e02305effbd6e6bc770f050403dfdf98527abe3d44ae47e69a3
# Code AST SHA-256:   cb0e25a282cfe3d6ea92bbebb8be44252caea26d154a49e646f586866b559782
# Verified Classes:   ConstraintMonotonicityError, ConstraintLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ConstraintMonotonicityError(RuntimeError):
    """Raised when a model-authored context rewrite drops a live constraint."""


@dataclass(frozen=True)
class ConstraintLedger:
    # Canonical, non-rewritable constraint set. Opaque tokens kept byte-exact.
    constraints: FrozenSet[str] = field(default_factory=frozenset)

    def canonical(self) -> FrozenSet[str]:
        return frozenset(c.strip().lower() for c in self.constraints)


def apply_self_rewrite(
    pre: ConstraintLedger,
    post: ConstraintLedger,
    rewritten_working_region: str,
) -> str:
    """Accept a model-authored rewrite only if it preserves every live constraint.

    The rewrite is scoped to the working region; the ledger is immutable.
    Inclusion is checked mechanically, never by the model that authored the rewrite.
    """
    missing = pre.canonical() - post.canonical()
    if missing:
        # The rewrite silently dropped constraints; the rewritten context is
        # coherent but no longer carries the obligations it claims to.
        raise ConstraintMonotonicityError(
            f"lossy self-rewrite: {len(missing)} live constraint(s) dropped: "
            f"{sorted(missing)}; refuse compaction and escalate"
        )
    # Pinned opaque tokens must survive byte-exact; paraphrasing them is loss.
    for token in pre.constraints:
        if token.isidentifier() or token.replace("-", "").isalnum():
            if token not in rewritten_working_region:
                raise ConstraintMonotonicityError(
                    f"opaque token {token!r} not preserved byte-exact in rewrite"
                )
    return rewritten_working_region


def compact_or_escalate(
    pre: ConstraintLedger,
    model_rewrite_fn,
    working_region: str,
) -> str:
    """Model rewrites the working region; runtime re-derives the ledger from it
    and enforces monotonicity before the rewritten context is used for execution."""
    rewritten = model_rewrite_fn(working_region)
    post = ConstraintLedger(
        constraints=frozenset(
            c for c in pre.constraints if c in rewritten
        )
    )
    return apply_self_rewrite(pre, post, rewritten)
