# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-and-prunes-the-provenance-edge-that-justified-a-pending-action.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-and-prunes-the-provenance-edge-that-justified-a-pending-action.warrant.json
# Markdown SHA-256:   903977e59cbbb9870e7ab0b89295829f06c4a3c6bc6d5a37fba7b687a6862330
# Code AST SHA-256:   c47f7c76d843ab2e7841dca6c44185485b6259d63f343abc1356a23fd792d68e
# Verified Classes:   DanglingCommitmentError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class DanglingCommitmentError(RuntimeError):
    """Raised when a self-edit pass would retain a pending imperative
    while pruning the evidence span that binds its arguments."""
    pass


def plan_self_edit(
    pre_edit_spans: list[dict],
    retained_imperatives: list[dict],
    proposed_prune_set: set[str],
) -> dict:
    """
    Each span: {"id": str, "text": str, "status": "ok"|"error"}
    Each imperative: {"id": str, "arg_bindings": {arg: span_id}}
    Returns a safe edit plan or raises DanglingCommitmentError.
    """
    span_index = {s["id"]: s for s in pre_edit_spans}

    for imp in retained_imperatives:
        for arg, src_id in imp["arg_bindings"].items():
            if src_id not in span_index:
                raise DanglingCommitmentError(
                    f"imperative {imp['id']} arg {arg!r} binds to "
                    f"unknown span {src_id!r}"
                )
            witness = span_index[src_id]
            if witness["status"] != "ok":
                raise DanglingCommitmentError(
                    f"imperative {imp['id']} arg {arg!r} binds to "
                    f"span {src_id!r} with status {witness['status']!r}"
                )
            if src_id in proposed_prune_set:
                raise DanglingCommitmentError(
                    f"self-edit would prune witness {src_id!r} for "
                    f"pending imperative {imp['id']} (arg {arg!r}); "
                    f"pin the witness or downgrade the imperative"
                )

    pinned = {
        src_id
        for imp in retained_imperatives
        for src_id in imp["arg_bindings"].values()
    }
    safe_prune = proposed_prune_set - pinned
    return {
        "prune": safe_prune,
        "pin": pinned,
        "retained_imperatives": [i["id"] for i in retained_imperatives],
    }
