# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-context-policy-into-a-self-ratifying-loop-that-no-longer-admits-contradicting-tool-output.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-context-policy-into-a-self-ratifying-loop-that-no-longer-admits-contradicting-tool-output.warrant.json
# Markdown SHA-256:   a18f6b3844ac6c1440232f41fef179780e8f928d430635d34aebe1f57991c01f
# Code AST SHA-256:   d43e5420ea47984dcd08598c14d7cfeb8ce78194a35e6917b9b40e92be23fdf8
# Verified Classes:   SelfRatifyingPolicyError, ProvenanceHandle, PolicyRewrite
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SelfRatifyingPolicyError(RuntimeError):
    """Raised when a context-policy rewrite is justified only by material the
    in-force policy itself summarized or evicted (closed under its own
    justification)."""
    pass


@dataclass
class ProvenanceHandle:
    claim: str
    raw_uri: Optional[str]          # resolvable pointer to un-summarized source
    produced_by_policy: bool        # True if only a summary backs this claim


@dataclass
class PolicyRewrite:
    new_policy: str
    rationale: list[ProvenanceHandle] = field(default_factory=list)


def validate_rewrite(rewrite: PolicyRewrite, pre_rewrite_policy: str) -> None:
    """Enforce the invariant: no policy may be adopted on evidence that the
    pre-rewrite policy had already made unretrievable."""
    if not rewrite.rationale:
        raise SelfRatifyingPolicyError(
            "rewrite carries no provenance handles; agent evaluated its own "
            "summary of the policy, not the policy"
        )
    for h in rewrite.rationale:
        if h.produced_by_policy or h.raw_uri is None:
            raise SelfRatifyingPolicyError(
                f"claim {h.claim!r} resolves only to policy-produced summary "
                f"under policy {pre_rewrite_policy!r}; rewrite is "
                f"self-ratifying and must be rejected pending raw re-fetch"
            )
    # A rewrite that lowers retrievability of its own justification is inadmissible.
    for h in rewrite.rationale:
        if not _retrievable_after(h.raw_uri, rewrite.new_policy):
            raise SelfRatifyingPolicyError(
                f"new policy evicts {h.raw_uri!r}, the source that justified "
                f"its own adoption; loop would close"
            )


def _retrievable_after(raw_uri: str, new_policy: str) -> bool:
    # Stub: real implementation checks new_policy's eviction rules against the URI.
    return True
