# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-the-very-span-it-is-reasoning-inside.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-the-very-span-it-is-reasoning-inside.warrant.json
# Markdown SHA-256:   c3fad4c06d6c2d6fd8d75593a2d9d8772f933cc3855fd1f20b229a5ecc855e71
# Code AST SHA-256:   aac8918c1e450792ca944b553ef41e189c467e583b76aeffccf2ff92a7d77b5c
# Verified Classes:   InFlightSpanEvictionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class InFlightSpanEvictionError(RuntimeError):
    """Raised when a self-prune would evict a span the current reasoning step depends on."""
    pass


def apply_self_prune(
    window: list[dict],
    prune_block: list[dict],
    in_flight_refs: set[str],
    measured_summarization_cost: int,
    soft_budget: int,
) -> list[dict]:
    """
    Apply a model-emitted PRUNE block under the disjointness and
    temporal-separation invariants.

    prune_block: [{"span_id": str, "relevance": float, "action": "evict"|"summarize"}]
    in_flight_refs: span_ids the current derivation depends on (harness-computed,
                    not model-reported, because the model cannot reliably self-classify).
    """
    named = {p["span_id"] for p in prune_block}

    # Invariant 1: no in-flight span may be evicted or rewritten this turn.
    collision = named & in_flight_refs
    if collision:
        raise InFlightSpanEvictionError(
            f"prune targets in-flight spans {sorted(collision)}; "
            f"defer to next turn or drop from block"
        )

    # Invariant 2: projected savings must be net of summarization cost.
    evictable = [p for p in prune_block if p["span_id"] not in in_flight_refs]
    projected = sum(
        len(next(s for s in window if s["id"] == p["span_id"])["content"])
        for p in evictable
    )
    if projected - measured_summarization_cost <= 0:
        # Savings-neutral or negative: defer rather than oscillate.
        return window

    # Invariant 3: apply, then require the caller to re-measure the window
    # after the summary lands. Projected size is not authoritative.
    kept = [s for s in window if s["id"] not in {p["span_id"] for p in evictable}]
    summary = {
        "id": "__summary__",
        "content": " ".join(
            next(s for s in window if s["id"] == p["span_id"])["content"][:200]
            for p in evictable
        ),
    }
    result = kept + [summary]

    if len(str(result)) > soft_budget and projected <= measured_summarization_cost:
        raise InFlightSpanEvictionError(
            "post-edit window exceeds budget while net savings were non-positive; "
            "prune was invalid and must be rolled back from checkpoint"
        )
    return result
