# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-rewrite-its-own-context-when-the-rewrite-operator-is-non-idempotent-under-re-entry.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-rewrite-its-own-context-when-the-rewrite-operator-is-non-idempotent-under-re-entry.warrant.json
# Markdown SHA-256:   c36d9d0156ceb00668b85ebc5958ff9d851d9f0ace40d09c1f462249ac7a76f4
# Code AST SHA-256:   ec7ec382ef79161f58c96aece7df26faebc3306dc73f83d08512f7354550b20f
# Verified Classes:   UnanchorableRewriteError, ScopeWideningError, Claim, RewriteState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class UnanchorableRewriteError(RuntimeError):
    """Raised when a rewrite would re-compress material with no resolvable source."""
    pass

class ScopeWideningError(RuntimeError):
    """Raised when a rewrite widens a negative/quantitative claim beyond its source."""
    pass

@dataclass
class Claim:
    text: str
    source_range: Optional[tuple[int, int]]   # None => unanchorable (source evicted)
    scope: str                                 # e.g. "src/", "repo", "module:x"

@dataclass
class RewriteState:
    anchor: str                                # frozen objective + constraints (P1)
    claims: list[Claim] = field(default_factory=list)
    rewrite_depth: int = 0

def rewrite(state: RewriteState, budget: int, rewriter) -> RewriteState:
    # P1: anchor is never passed to the rewriter; it is re-injected after.
    compressible, frozen = [], []
    for c in state.claims:
        (compressible if c.source_range is not None else frozen).append(c)

    # P2 gate: any unanchorable claim that the rewriter wants to touch is a hard stop.
    if frozen and rewriter.wants_to_touch(frozen):
        raise UnanchorableRewriteError(
            f"rewrite depth {state.rewrite_depth}: {len(frozen)} claim(s) have no "
            f"resolvable source and cannot be re-compressed; halt or retrieve source"
        )

    new_claims = rewriter.compress(compressible)  # source-derived only

    # P3 gate: scope may not widen relative to source.
    for old, new in zip(compressible, new_claims):
        if new.scope != old.scope and _is_widening(old.scope, new.scope):
            raise ScopeWideningError(
                f"claim scope widened {old.scope!r} -> {new.scope!r}: {old.text!r}"
            )

    # P4 gate: idempotence check on the frozen source before committing depth.
    if state.rewrite_depth >= 1:
        replay = rewriter.compress(new_claims)
        if not _token_equivalent(replay, new_claims, tol=0.05):
            raise UnanchorableRewriteError(
                "rewrite operator non-idempotent on source; refusing second-order rewrite"
            )

    if _size(new_claims) + _size(frozen) + _size(state.anchor) > budget:
        raise UnanchorableRewriteError(
            "budget cannot be met without pruning unanchorable claims; fail closed"
        )

    return RewriteState(
        anchor=state.anchor,
        claims=new_claims + frozen,
        rewrite_depth=state.rewrite_depth + 1,
    )

def _is_widening(old: str, new: str) -> bool:
    return new in ("repo", "tree", "*") and old not in ("repo", "tree", "*")

def _token_equivalent(a, b, tol: float) -> bool:
    return abs(_size(a) - _size(b)) / max(_size(b), 1) <= tol

def _size(x) -> int:
    return sum(len(c.text.split()) for c in x) if isinstance(x, list) else len(str(x).split())
