# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-prune-speculative-branches-without-discarding-the-one-branch-that-later-becomes-load-bearing.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-prune-speculative-branches-without-discarding-the-one-branch-that-later-becomes-load-bearing.warrant.json
# Markdown SHA-256:   bb68e728f2116f766d79152a501561259f513e9f91a87d1c19f4ffad222b0852
# Code AST SHA-256:   ef25957c52a969ceea4c90b43299c4afa1d445b0aa8eca658fbae7751df3fbe3
# Verified Classes:   OrphanedDependencyPruneError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class OrphanedDependencyPruneError(RuntimeError):
    """Raised when a prune decision would leave a surviving branch referencing
    a pruned branch's output without a recorded dependency edge."""
    pass


def prune_branches(branches, deps, merit_scores, threshold):
    """
    branches: dict[branch_id -> partial_plan_text]
    deps:     dict[branch_id -> set[branch_id]]  # recorded typed dependency edges
    merit_scores: dict[branch_id -> float]       # local confidence / token merit
    threshold: float                             # tie-breaker cutoff for prunable set
    """
    # 1. Candidates are only branches with known, zero out-degree.
    prunable = []
    for bid in branches:
        if bid not in deps:
            # Unknown out-degree is treated as infinite: never prune.
            continue
        if len(deps[bid]) == 0 and merit_scores.get(bid, 0.0) < threshold:
            prunable.append(bid)

    # 2. Simulate the prune and check for orphan references.
    pruned = set(prunable)
    surviving = set(branches) - pruned
    orphans = {}
    for bid in surviving:
        text = branches[bid].lower()
        for pid in pruned:
            # A surviving branch that names a pruned branch's output
            # is an orphan reference unless a typed edge exists.
            if pid in text and pid not in deps.get(bid, set()):
                orphans.setdefault(bid, set()).add(pid)

    if orphans:
        raise OrphanedDependencyPruneError(
            f"prune of {sorted(pruned)} would orphan references in "
            f"{ {k: sorted(v) for k, v in orphans.items()} }; "
            f"suspend or merge instead of prune"
        )

    return pruned
