# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-policy-self-corruption-when-a-context-rewriting-rule-edits-its-own-governing-prompt.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-policy-self-corruption-when-a-context-rewriting-rule-edits-its-own-governing-prompt.warrant.json
# Markdown SHA-256:   5d1c9bfe4e9a327706e84fe2d92afd751f14f08e457395ea7e7d141050d9fc6c
# Code AST SHA-256:   74137727d98e6e3e8a0bcc9e19a3604c0b3aadecd9e735c528f567733331197d
# Verified Classes:   PolicySubstrateCorruption
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PolicySubstrateCorruption(RuntimeError):
    """Raised when a context rewrite mutates or removes its own governing directives."""


POLICY_REGION = (0, 600)  # token range [start, end) holding the directive block


def apply_rewrite(span: tuple[int, int], directives_before: frozenset[str],
                  directives_after: frozenset[str], mutable_fields: frozenset[str]) -> None:
    start, end = span
    p_start, p_end = POLICY_REGION

    # Invariant 1: substrate disjointness. A rewrite may not touch the policy region
    # unless it is an explicitly whitelisted in-place field edit.
    intersects = start < p_end and p_start < end
    if intersects and not mutable_fields:
        raise PolicySubstrateCorruption(
            f"rewrite span {span} intersects policy region {POLICY_REGION}; "
            "directive block cannot authorize its own mutation"
        )

    # Invariant 2: post-condition diff. Directives must be bit-identical after rewrite.
    removed = directives_before - directives_after
    added = directives_after - directives_before
    if removed or added:
        raise PolicySubstrateCorruption(
            f"directive set changed across rewrite: removed={sorted(removed)} "
            f"added={sorted(added)}; authority must be monotonic (tighten only)"
        )


def prune_under_budget(candidates: list[tuple[int, int]], budget_tokens: int,
                       directives: frozenset[str]) -> list[tuple[int, int]]:
    evicted = []
    freed = 0
    for span in sorted(candidates, key=lambda s: s[0]):  # staleness order upstream
        if freed >= budget_tokens:
            break
        # Executor refuses to evict a span whose removal would drop a directive.
        if span[0] < POLICY_REGION[1] and span[1] > POLICY_REGION[0]:
            raise PolicySubstrateCorruption(
                f"eviction candidate {span} overlaps policy region; "
                "recency scoring must exclude directive-bearing spans"
            )
        evicted.append(span)
        freed += span[1] - span[0]
    return evicted
