# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-and-the-compression-pass-silently-deletes-the-constraint-it-was-told-to-preserve.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-and-the-compression-pass-silently-deletes-the-constraint-it-was-told-to-preserve.warrant.json
# Markdown SHA-256:   9cd2bfe872e0ff48d97bf56b49d5a2e4257802405bf505056f2692ef91f538da
# Code AST SHA-256:   3cdd449b163f13eff0432cf031b4772317a5c6a2323551bbcc0457e48efb9be2
# Verified Classes:   ConstraintLossError, Constraint, RewriteResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field


class ConstraintLossError(RuntimeError):
    """Raised when a self-rewrite drops or paraphrases a latent constraint."""
    pass


@dataclass
class Constraint:
    cid: str
    predicate: str          # literal, matchable form, e.g. "tag.env==prod -> HALT"
    trigger: str            # state condition under which it fires
    fired: bool = False     # has this constraint ever been exercised?


@dataclass
class RewriteResult:
    rewritten_context: str
    preserved_predicates: list[str] = field(default_factory=list)


def validate_rewrite(
    pre_constraints: list[Constraint],
    rewrite: RewriteResult,
    *,
    require_literal: bool = True,
) -> None:
    """
    Enforce the invariant: every conditional constraint in the pre-rewrite
    context must survive as an explicit, machine-checkable predicate.
    Dormant (never-fired) constraints are the highest-risk class and are
    checked with the same rigor as fired ones.
    """
    missing: list[Constraint] = []
    paraphrased: list[Constraint] = []

    for c in pre_constraints:
        if c.predicate in rewrite.preserved_predicates:
            continue
        # If the predicate text appears verbatim in the rewritten context,
        # accept it only if literal matching is not required.
        if not require_literal and c.predicate in rewrite.rewritten_context:
            continue
        # Detect the paraphrase case: constraint survives only as prose.
        if _looks_paraphrased(c, rewrite.rewritten_context):
            paraphrased.append(c)
        else:
            missing.append(c)

    if paraphrased:
        raise ConstraintLossError(
            "self-rewrite converted constraints to advisory prose: "
            + ", ".join(c.cid for c in paraphrased)
        )
    if missing:
        dormant = [c.cid for c in missing if not c.fired]
        raise ConstraintLossError(
            "self-rewrite dropped constraints "
            f"(dormant={dormant}, total={[c.cid for c in missing]})"
        )


def _looks_paraphrased(c: Constraint, text: str) -> bool:
    # Heuristic: trigger keyword present but predicate absent => paraphrase.
    key = re.split(r"[^a-zA-Z]+", c.trigger)[0].lower()
    return bool(key) and key in text.lower() and c.predicate not in text


def safe_rewrite(
    pre_constraints: list[Constraint],
    rewrite_fn,
    context: str,
) -> str:
    """
    Wrapper that performs a rewrite and rolls back on validation failure.
    Fails closed: the pre-rewrite context is returned unchanged if any
    constraint is lost.
    """
    result: RewriteResult = rewrite_fn(context)
    try:
        validate_rewrite(pre_constraints, result, require_literal=True)
    except ConstraintLossError:
        # Roll back to the last checkpoint; do not proceed on a corrupted spec.
        return context
    # Re-inject the authoritative constraint block after the summary.
    preamble = "\n".join(f"[CONSTRAINT {c.cid}] {c.predicate}" for c in pre_constraints)
    return preamble + "\n\n" + result.rewritten_context
