# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-premature-pruning-of-a-still-viable-speculative-branch-in-parallel-sub-agent-hypothesis-exploration.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-premature-pruning-of-a-still-viable-speculative-branch-in-parallel-sub-agent-hypothesis-exploration.warrant.json
# Markdown SHA-256:   5f22c713574e31543498fd883599e31795ded763598bc22409e33555e5434130
# Code AST SHA-256:   23a0fbb51682f9313faf5aa5841c6ef6aa4526a3339cf239113dfa5919a6b05b
# Verified Classes:   PrematurePruneError, Branch, PruneDecision
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class PrematurePruneError(RuntimeError):
    """Raised when a branch is pruned without a subsumption witness or while climbing."""
    pass


@dataclass
class Branch:
    branch_id: str
    hypothesis: str
    score_history: list = field(default_factory=list)

    def slope(self, window: int = 3) -> float:
        if len(self.score_history) < 2:
            return 0.0
        recent = self.score_history[-window:]
        if len(recent) < 2:
            return 0.0
        return (recent[-1] - recent[0]) / (len(recent) - 1)


@dataclass
class PruneDecision:
    branch_id: str
    witness_branch_id: Optional[str]
    reason: str


def prune_branches(
    branches: list,
    threshold: float,
    subsumption: dict,
) -> list:
    """
    subsumption maps pruned_branch_id -> surviving_branch_id that will test
    the same discriminator. Absence of a witness means the branch must be retained.
    """
    decisions = []
    for b in branches:
        if b.score_history and b.score_history[-1] >= threshold:
            continue  # above threshold, not a prune candidate

        # Guard 1: a climbing branch is live exploration, never prune.
        if b.slope() > 0.0:
            decisions.append(
                PruneDecision(b.branch_id, None, "retained: positive slope, live exploration")
            )
            continue

        # Guard 2: no subsumption witness means the branch discriminates
        # against the surviving consensus; it must be retained and flagged.
        witness = subsumption.get(b.branch_id)
        if witness is None:
            decisions.append(
                PruneDecision(b.branch_id, None, "retained: no subsumption witness, dissenting")
            )
            continue

        # Guard 3: the witness must actually exist in the surviving population.
        if witness not in {x.branch_id for x in branches}:
            raise PrematurePruneError(
                f"branch {b.branch_id} pruned against witness {witness} "
                f"that is not in the surviving population"
            )

        decisions.append(
            PruneDecision(b.branch_id, witness, "pruned: subsumed by surviving branch")
        )
    return decisions


def apply_prune(decisions: list, branches: list) -> list:
    survivors = []
    for b in branches:
        d = next((d for d in decisions if d.branch_id == b.branch_id), None)
        if d is None:
            survivors.append(b)
            continue
        if d.witness_branch_id is None:
            survivors.append(b)  # retained by guard
            continue
        # Final invariant: a witness-free or climbing prune is a bug, not a policy.
        if b.slope() > 0.0:
            raise PrematurePruneError(
                f"attempted to drop climbing branch {b.branch_id} "
                f"(slope={b.slope():.3f}) under witness {d.witness_branch_id}"
            )
    return survivors
