# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-self-editing-context-policy-from-pruning-the-evidence-that-justifies-its-own-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-self-editing-context-policy-from-pruning-the-evidence-that-justifies-its-own-rewrite.warrant.json
# Markdown SHA-256:   82a23e40088c57f57a53dc8acfe4840bae0f59c32a99f13be695744dcf52a4ff
# Code AST SHA-256:   d55e147e0b725b1894670acbdd17ecd86906e8676ce482418627b136f0804541
# Verified Classes:   ProvenanceClosureViolation, Claim, RewriteCandidate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceClosureViolation(RuntimeError):
    """Raised when a context rewrite severs the support graph of a retained claim."""


@dataclass
class Claim:
    text: str
    supporting_token_ids: frozenset[int]
    external_pointer: Optional[str] = None
    unsupported: bool = False


@dataclass
class RewriteCandidate:
    retained_token_ids: frozenset[int]
    claims: list[Claim] = field(default_factory=list)


def enforce_provenance_closure(
    candidate: RewriteCandidate,
    pre_rewrite_token_ids: frozenset[int],
) -> None:
    """
    Reject a rewrite candidate if any retained claim loses all support in the
    same pass without an external pointer or an explicit unsupported marker.

    A claim is closed iff, for every supporting token that existed before the
    rewrite, at least one of the following holds:
      - the token is retained in the candidate, or
      - the claim carries an external_pointer to an authoritative record, or
      - the claim is explicitly marked unsupported.
    """
    for claim in candidate.claims:
        lost = claim.supporting_token_ids - candidate.retained_token_ids
        if not lost:
            continue
        if claim.external_pointer:
            continue
        if claim.unsupported:
            continue
        # Support was removed in the same pass with no replacement record.
        raise ProvenanceClosureViolation(
            f"claim {claim.text!r} lost support tokens {sorted(lost)} "
            f"with no external_pointer and no unsupported marker; "
            f"rewrite would launder its own justification"
        )


def select_rewrite(
    candidates: list[RewriteCandidate],
    pre_rewrite_token_ids: frozenset[int],
    reward_fn,
) -> RewriteCandidate:
    """
    Score only closure-satisfying candidates. A candidate that violates closure
    is never scored, so the reward model cannot select for evidence deletion.
    """
    admissible: list[RewriteCandidate] = []
    for cand in candidates:
        try:
            enforce_provenance_closure(cand, pre_rewrite_token_ids)
        except ProvenanceClosureViolation:
            continue  # rejected before reward sees it
        admissible.append(cand)

    if not admissible:
        raise ProvenanceClosureViolation(
            "no rewrite candidate satisfies provenance closure; "
            "fall back to retention or external-log pointer emission"
        )

    return max(admissible, key=reward_fn)
