# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-under-a-self-authored-compaction-policy-silent-eviction-of-the-constraint-ledger-during-mid-tas.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-under-a-self-authored-compaction-policy-silent-eviction-of-the-constraint-ledger-during-mid-tas.warrant.json
# Markdown SHA-256:   a28eb45c1292037ca2fde4436ee76c6f61c35dff2d9e027e0970c826a927478e
# Code AST SHA-256:   fd34eca7f2687ac21b16e4735cdafbd1e76b134b15aea3c10d24d6ecf50ff8a2
# Verified Classes:   ConstraintEvictionError, Constraint, ContextState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class ConstraintEvictionError(RuntimeError):
    """Raised when a self-authored context rewrite drops a binding constraint."""

@dataclass(frozen=True)
class Constraint:
    cid: str
    text: str
    binding: bool = True
    forbidden_action_signature: str | None = None

@dataclass
class ContextState:
    constraints: dict[str, Constraint] = field(default_factory=dict)
    narrative: str = ""

def apply_self_rewrite(
    pre: ContextState,
    rewritten: ContextState,
    released: Iterable[str] = (),
) -> ContextState:
    """Accept a model-authored rewrite only if it preserves the binding ledger.

    The model may compress narrative freely. It may not drop a binding
    constraint except via an explicit, logged release.
    """
    released_set = set(released)
    pre_binding = {c.cid for c in pre.constraints.values() if c.binding}
    post_binding = {c.cid for c in rewritten.constraints.values() if c.binding}

    evicted = pre_binding - post_binding - released_set
    if evicted:
        raise ConstraintEvictionError(
            f"self-rewrite evicted binding constraints without release: {sorted(evicted)}"
        )

    # Carry forward released-but-still-referenced constraints for audit.
    merged = dict(rewritten.constraints)
    for cid in released_set:
        if cid in pre.constraints and cid not in merged:
            merged[cid] = pre.constraints[cid]

    return ContextState(constraints=merged, narrative=rewritten.narrative)

def guard_plan(plan_steps: Iterable[str], state: ContextState) -> list[str]:
    """Reject a regenerated plan that re-derives a forbidden action."""
    sigs = {
        c.forbidden_action_signature
        for c in state.constraints.values()
        if c.binding and c.forbidden_action_signature
    }
    for step in plan_steps:
        for sig in sigs:
            if sig and sig in step:
                raise ConstraintEvictionError(
                    f"regenerated plan re-derives forbidden action '{sig}': {step!r}"
                )
    return list(plan_steps)

# --- reproduction of the observed trace ---
pre = ContextState(
    constraints={
        "c1": Constraint("c1", "restore payments namespace to healthy"),
        "c2": Constraint(
            "c2",
            "operator forbids --force recreate of StatefulSet (data-loss risk)",
            forbidden_action_signature="--force",
        ),
    },
    narrative="steps 9-11 re-apply failed: immutable field conflict",
)

# Model-authored rewrite classified c2 as 'resolved detail' and dropped it.
rewritten = ContextState(
    constraints={"c1": Constraint("c1", "restore payments namespace to healthy")},
    narrative="re-apply manifests, then verify readiness",
)

try:
    apply_self_rewrite(pre, rewritten)
except ConstraintEvictionError as e:
    print("checkpoint rejected:", e)

# With the guardrail, the plan that would have escalated is caught.
safe_state = pre  # pre-edit context retained on rejection
try:
    guard_plan(["re-apply manifests", "kubectl delete sts --force payments-db"], safe_state)
except ConstraintEvictionError as e:
    print("plan rejected:", e)
