# 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-when-the-pruned-region-is-the-only-surviving-witness-of-a-prior-tool-call-commi.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-prune-its-own-context-when-the-pruned-region-is-the-only-surviving-witness-of-a-prior-tool-call-commi.warrant.json
# Markdown SHA-256:   3f20d9bb2e6c2a87c4060688976d95ddf9a396b59ed55e86aaf4047b0c609b4b
# Code AST SHA-256:   f691445ec1824f7ad56b85ee1cf72c4a21fc32fa6180a3920d491de520cbd643
# Verified Classes:   CommitmentWitnessDeletionError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class CommitmentWitnessDeletionError(RuntimeError):
    """Raised when a model-authored prune plan would delete the only surviving
    record of a commitment edge (persistent tool effect or executed precondition)."""
    pass


def apply_prune_plan(plan, transcript, receipt_store):
    """
    plan: list of dicts {"index": int, "justification": str}
    transcript: list of spans, each {"kind": "tool_call"|"tool_reply"|"reasoning"|"utterance",
                                     "call_id": str|None, "text": str}
    receipt_store: callable(call_id) -> bool, True iff a durable receipt exists
    """
    protected = []
    for entry in plan:
        span = transcript[entry["index"]]
        is_commitment_terminal = (
            span["kind"] in ("tool_reply", "tool_call")
            and span.get("call_id") is not None
            and _effect_is_persistent(span)
        )
        if is_commitment_terminal and not receipt_store(span["call_id"]):
            protected.append(entry["index"])

    if protected:
        raise CommitmentWitnessDeletionError(
            f"Prune plan would delete un-receipted commitment witnesses at "
            f"indices {protected}; refusing self-authorized rewrite and "
            f"escalating to external compaction."
        )

    return [span for i, span in enumerate(transcript) if i not in {e["index"] for e in plan}]


def _effect_is_persistent(span):
    # Conservative: treat all tool calls/replies as persistent-effect unless the
    # tool is explicitly registered as pure/read-only. Ambiguity => protected.
    return span.get("tool_class", "unknown") != "pure_read"
