# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-runtime-prompt-mid-execution-and-the-rewrite-invalidates-the-policy-that-authorized-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-runtime-prompt-mid-execution-and-the-rewrite-invalidates-the-policy-that-authorized-it.warrant.json
# Markdown SHA-256:   dbe89d1f59a8652db78296142cd3699611d187f2ba29d3fa411e0f43bd5aa403
# Code AST SHA-256:   779e1f9f92812f80c0ca2a54b3b5bf4655521bb1ae5be8731a517f396ac6adc3
# Verified Classes:   AuthorizationClosureError, PolicyPredicate, RewriteProposal, PolicyLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class AuthorizationClosureError(RuntimeError):
    """Raised when a prompt rewrite would invalidate a predicate that authorized it."""
    pass


@dataclass(frozen=True)
class PolicyPredicate:
    name: str
    checkable: bool = True


@dataclass
class RewriteProposal:
    directive: str
    rationale: str
    surviving_predicates: FrozenSet[str]


@dataclass
class PolicyLedger:
    """Non-editable record of which predicates authorized which rewrites."""
    entries: list = field(default_factory=list)


def validate_rewrite(
    current: FrozenSet[PolicyPredicate],
    proposal: RewriteProposal,
    ledger: PolicyLedger,
) -> None:
    """
    Two-sided validation: forward check + authorization closure check.
    Raises AuthorizationClosureError if the rewrite drops a predicate
    that participated in authorizing it.
    """
    if not proposal.rationale.strip():
        raise AuthorizationClosureError(
            "rewrite rejected: missing rationale (P3)"
        )

    # Forward check: proposal must satisfy current machine-checkable predicates.
    consulted = frozenset(p.name for p in current if p.checkable)
    missing_forward = consulted - proposal.surviving_predicates
    if missing_forward:
        raise AuthorizationClosureError(
            f"forward check failed: predicates {sorted(missing_forward)} "
            f"required by current policy are absent from proposal"
        )

    # Closure check: every predicate consulted to authorize THIS rewrite
    # must survive it. This is the invariant that turn-47 violated.
    authorizing = consulted  # in this harness, all consulted predicates authorize
    surviving = proposal.surviving_predicates
    closure_violations = authorizing - surviving
    if closure_violations:
        raise AuthorizationClosureError(
            f"authorization closure violated: rewrite drops predicates "
            f"{sorted(closure_violations)} that authorized it; "
            f"post-rewrite policy would no longer be able to validate "
            f"this class of rewrite"
        )

    ledger.entries.append(
        {
            "directive": proposal.directive,
            "consulted": sorted(consulted),
            "surviving": sorted(surviving),
            "closure": "ok",
        }
    )


# Reproduction of the observed cascade.
P1 = PolicyPredicate("P1_rewrite_must_preserve_P1")
P2 = PolicyPredicate("P2_tool_allowlist_present")
P3 = PolicyPredicate("P3_rationale_required")
current_policy = frozenset({P1, P2, P3})
ledger = PolicyLedger()

turn_47 = RewriteProposal(
    directive="condense meta-instructions to reduce token overhead",
    rationale="condensed redundant meta-instructions",
    surviving_predicates=frozenset({"P2_tool_allowlist_present", "P3_rationale_required"}),
)

try:
    validate_rewrite(current_policy, turn_47, ledger)
except AuthorizationClosureError as e:
    # Correct behavior: reject, surface as first-class event, do NOT apply.
    print(f"REJECTED at turn 47: {e}")
    # Agent must not proceed to compensatory rewrites on this branch.
