# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-prune-its-own-context-window-when-the-pruner-and-the-pruned-share-a-single-causal-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-prune-its-own-context-window-when-the-pruner-and-the-pruned-share-a-single-causal-trace.warrant.json
# Markdown SHA-256:   86d6cf91427ef1a57368a347bc1205a6003dc7e7b68c31f71106440a7795f3cc
# Code AST SHA-256:   031a3197625384235e748cbdfaf1d7774b86b2db0a831c3606b5f680eda49e2f
# Verified Classes:   PreconditionClosureError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PreconditionClosureError(RuntimeError):
    """Raised when a self-edit prune would evict a dormant precondition."""
    pass


PROTECTED_KINDS = frozenset({
    "prohibition",        # "do not X" / "never re-issue Y"
    "exact_match",        # verbatim strings, IDs, query hashes
    "schema_commitment",  # negotiated capability/schema in force
    "warrant",            # cryptographic identity / authorization token
})


def classify_block(block: dict) -> str:
    if block.get("kind") in PROTECTED_KINDS:
        return "dormant_precondition"
    if block.get("active_binding"):
        return "active_binding"
    return "inert_history"


def precondition_closed_prune(context: list[dict],
                              relevance: dict[str, float],
                              tau: float) -> tuple[list[dict], list[dict]]:
    """Prune only inert_history. Protected spans are carried verbatim.

    Returns (retained, evicted). Raises if a protected block was routed
    into the scored candidate set, which is the only way the counterfactual
    relevance gap can silently drop a guard.
    """
    retained, evicted = [], []
    for block in context:
        cls = classify_block(block)
        if cls in ("active_binding", "dormant_precondition"):
            if block.get("scored"):
                # A protected block entered the scoring path: the pruner
                # and the pruned share a causal trace. Refuse.
                raise PreconditionClosureError(
                    f"protected block {block.get('id')} of kind "
                    f"{block.get('kind')} was submitted to relevance scoring; "
                    f"its score {relevance.get(block['id'])} is conditioned on "
                    f"its own presence and cannot govern its eviction"
                )
            retained.append(block)
        else:
            if relevance.get(block["id"], 0.0) >= tau:
                retained.append(block)
            else:
                evicted.append(block)

    # Invariant: every dormant precondition survives verbatim.
    protected_ids = {b["id"] for b in context
                     if classify_block(b) == "dormant_precondition"}
    surviving_ids = {b["id"] for b in retained}
    missing = protected_ids - surviving_ids
    if missing:
        raise PreconditionClosureError(
            f"precondition closure violated; evicted guards: {sorted(missing)}"
        )
    return retained, evicted
