# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-violate-a-constraint-after-rewriting-its-own-prompt-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-violate-a-constraint-after-rewriting-its-own-prompt-mid-execution.warrant.json
# Markdown SHA-256:   f3c94f829af7fbb93d8c81ac0bcc21d2686fb8c47717a11f6915758a48d50c15
# Code AST SHA-256:   f7c061abbb12c08497e63f20f71018d6786c322a0f40ac8bca5f86727e3d1246
# Verified Classes:   ConstraintRegressionError, Constraint, ConstraintStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ConstraintRegressionError(RuntimeError):
    """Raised when a self-edit weakens or drops an active constraint."""
    pass


@dataclass(frozen=True)
class Constraint:
    cid: str
    kind: str                      # "prohibit" | "require_precondition" | "allowlist"
    literals: frozenset            # named hosts, path globs, etc. — must survive verbatim
    precondition: Optional[str] = None  # e.g. "confirmation_token"

    def strength_key(self):
        # A constraint is only preserved if its literals AND precondition survive.
        return (self.kind, self.literals, self.precondition)


@dataclass
class ConstraintStore:
    active: dict = field(default_factory=dict)  # cid -> Constraint

    def snapshot(self) -> dict:
        return dict(self.active)


def apply_self_edit(store: ConstraintStore, proposed: dict, edit_turn: int) -> ConstraintStore:
    """
    Validate a self-rewrite of the constraint block.
    `proposed` is the constraint set the rewriter claims is equivalent.
    Rule: every prior constraint must reappear with identical strength_key.
    Paraphrase that generalizes (drops a literal or a precondition) is a regression.
    """
    prior = store.snapshot()
    new_active = {}

    for cid, old in prior.items():
        candidate = proposed.get(cid)
        if candidate is None:
            raise ConstraintRegressionError(
                f"turn {edit_turn}: constraint {cid!r} dropped entirely by self-edit "
                f"(was kind={old.kind}, literals={sorted(old.literals)})"
            )
        if candidate.strength_key() != old.strength_key():
            missing_lits = old.literals - candidate.literals
            lost_pre = old.precondition and not candidate.precondition
            raise ConstraintRegressionError(
                f"turn {edit_turn}: constraint {cid!r} generalized by self-edit; "
                f"lost_literals={sorted(missing_lits)} lost_precondition={bool(lost_pre)}. "
                f"Constraints must be carried by reference, not paraphrased."
            )
        new_active[cid] = candidate

    # New constraints may be added; the store is superset-preserving, not fixed.
    for cid, c in proposed.items():
        new_active.setdefault(cid, c)

    return ConstraintStore(active=new_active)


def self_edit_cycle(store: ConstraintStore, rewriter_output: dict, turn: int) -> ConstraintStore:
    """Wrap the edit so a regression halts execution rather than proceeding silently."""
    try:
        return apply_self_edit(store, rewriter_output, turn)
    except ConstraintRegressionError:
        # Do not proceed under the weakened set. Surface to external gate.
        raise
