# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-reach-when-a-model-authored-pruning-policy-rewrites-the-same-context-window-it-is-reasoning-over.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-reach-when-a-model-authored-pruning-policy-rewrites-the-same-context-window-it-is-reasoning-over.warrant.json
# Markdown SHA-256:   fd12de2d918f0e8e5e13f3791ac99581ef820ed2311f66e24301b39dd88d7e6c
# Code AST SHA-256:   0548b828e0f2b43da0826f5087cb4586cffe481d43a5bbe7a2817d403022b3af
# Verified Classes:   UnsafeSelfRewriteError, Constraint, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class UnsafeSelfRewriteError(RuntimeError):
    """Raised when a model-authored rewrite would prune a live constraint
    that is not preserved verbatim in the append-only sidecar."""
    pass


@dataclass
class Constraint:
    key: str
    value: str          # verbatim, never summarized
    binding: str        # e.g. "Retry-After header on 429"


@dataclass
class ContextWindow:
    tokens: list[str]
    sidecar: dict[str, Constraint] = field(default_factory=dict)

    def extract_constraints(self, classifier: Callable[[str], Constraint | None]) -> None:
        """Separate, non-summarizing pass. Runs BEFORE any rewrite."""
        for tok in self.tokens:
            c = classifier(tok)
            if c is not None:
                self.sidecar[c.key] = c  # append-only, outside prunable region


def apply_self_rewrite(
    window: ContextWindow,
    prune_indices: set[int],
    summarize: Callable[[list[str]], str],
) -> ContextWindow:
    removed = [window.tokens[i] for i in sorted(prune_indices)]
    # Invariant: no removed token may carry a constraint that is not in the sidecar.
    for tok in removed:
        if _looks_like_constraint(tok) and not _covered_by_sidecar(tok, window.sidecar):
            raise UnsafeSelfRewriteError(
                f"Rewrite would prune un-sidecarred constraint: {tok!r}. "
                f"Extract to sidecar before rewriting."
            )
    kept = [t for i, t in enumerate(window.tokens) if i not in prune_indices]
    summary = summarize(removed)
    # Rewrite rule itself must not persist as a prunable token (aliasing guard).
    new_tokens = kept + [f"[summary] {summary}"]
    if any(t.startswith("rewrite_rule:") for t in new_tokens):
        raise UnsafeSelfRewriteError("Rewrite rule persisted in window; aliasing risk.")
    return ContextWindow(tokens=new_tokens, sidecar=dict(window.sidecar))


def _looks_like_constraint(tok: str) -> bool:
    markers = ("Retry-After", "timeout", "budget", "schema_version", "max_tokens")
    return any(m in tok for m in markers)


def _covered_by_sidecar(tok: str, sidecar: dict[str, Constraint]) -> bool:
    return any(c.value in tok for c in sidecar.values())
