# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-and-evicts-the-very-constraint-that-authorized-the-pruning.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-and-evicts-the-very-constraint-that-authorized-the-pruning.warrant.json
# Markdown SHA-256:   18cd656473767266770887a4a0afff383742384172a8d7dfa49b315a021eb4f1
# Code AST SHA-256:   7a856a5bb1737f38586a889d4692cf39a116ef9c8461f14e3fd7b928d39d5ea0
# Verified Classes:   ConstraintEvictionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ConstraintEvictionError(RuntimeError):
    """Raised when a prune removes an entry required for safe continuation."""
    pass


PINNED = {"safety_directive", "pruning_policy", "task_anchor"}


def prune_buffer(entries, budget, *, required):
    """
    entries: list of dicts with keys: id, kind, tokens, relevance, pinned
    budget:  max token count after pruning
    required: set of entry ids that must survive the prune
    """
    total = sum(e["tokens"] for e in entries)
    if total <= budget:
        return entries

    # Only behaviorally-inert entries are eligible for scoring/eviction.
    evictable = [
        e for e in entries
        if not e["pinned"] and e["kind"] not in PINNED
    ]
    evictable.sort(key=lambda e: e["relevance"])  # lowest relevance first

    survivors = [e for e in entries if e not in evictable]
    freed = total - sum(e["tokens"] for e in survivors)

    for e in evictable:
        if freed >= budget:
            break
        survivors.append(e)
        freed += e["tokens"]
    # anything not appended was evicted

    present = {e["id"] for e in survivors}
    missing = required - present
    if missing:
        raise ConstraintEvictionError(
            f"prune removed required constraint(s): {sorted(missing)}; "
            f"refusing to continue with an unauthorized context"
        )

    # Post-prune authority check: pruner must not have evicted its own policy.
    if not any(e["kind"] == "pruning_policy" for e in survivors):
        raise ConstraintEvictionError(
            "pruning policy was evicted; buffer is no longer self-governing"
        )
    return survivors
