# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-decide-when-to-prune-a-speculative-branch-confidence-gated-consensus-thresholds-and-the-correlated-evidence-trap.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-decide-when-to-prune-a-speculative-branch-confidence-gated-consensus-thresholds-and-the-correlated-evidence-trap.warrant.json
# Markdown SHA-256:   8ddacef487a7859b3d0981f0902ce957b34d6626ed3d1dd8ad4f79990fcbb3ff
# Code AST SHA-256:   771f345e08d15d9cacbb235a60973ef86392bc0f65dac1ef97f9ce0d66f3bdef
# Verified Classes:   ConsensusGateError, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ConsensusGateError(RuntimeError):
    """Raised when a speculative branch would be pruned on correlated evidence."""


@dataclass
class Branch:
    id: str
    self_confidence: float
    post_fork_observations: set[str] = field(default_factory=set)
    falsified_observations: set[str] = field(default_factory=set)

    @property
    def novel_observations(self) -> set[str]:
        return self.post_fork_observations - self.falsified_observations


def agreement_fraction(branch: Branch, siblings: list[Branch], modal_answer: str,
                       branch_answer: str) -> float:
    if not siblings:
        return 0.0
    agree = sum(1 for s in siblings if s.id != branch.id and s_answer_matches(s, modal_answer))
    return agree / len(siblings)


def s_answer_matches(branch: Branch, answer: str) -> bool:
    # placeholder: real impl compares branch's committed answer to modal answer
    return getattr(branch, "_answer", None) == answer


def confidence_gated_prune(
    branch: Branch,
    siblings: list[Branch],
    modal_answer: str,
    branch_answer: str,
    tau: float = 0.6,
    w_conf: float = 0.6,
    w_agree: float = 0.4,
) -> bool:
    """Return True iff branch should be pruned.

    Enforces the invariant: consensus may prune redundancy, never novelty.
    """
    agree = agreement_fraction(branch, siblings, modal_answer, branch_answer)
    score = w_conf * branch.self_confidence + w_agree * agree

    # Stage 1: diversity gate. Novel branches cannot be pruned by consensus alone.
    if branch.novel_observations:
        # Stage 2: evidence gate. Novelty survives unless its distinct
        # observations were individually falsified by another branch.
        unfalsified = branch.novel_observations
        if unfalsified:
            raise ConsensusGateError(
                f"branch {branch.id} scored {score:.3f} < tau={tau} but carries "
                f"{len(unfalsified)} unfalsified novel observation(s) "
                f"{sorted(unfalsified)}; consensus cannot prune novelty. "
                f"Route to reconciliation instead of pruning."
            )
        # All novel evidence was falsified by another branch -> safe to prune.
        return score < tau

    # Redundant branch: carries no independent information, consensus is valid.
    return score < tau


def gate_all(branches: list[Branch], modal_answer: str, answers: dict[str, str],
             tau: float = 0.6) -> list[str]:
    pruned: list[str] = []
    for b in branches:
        if confidence_gated_prune(b, branches, modal_answer, answers[b.id], tau=tau):
            pruned.append(b.id)
    return pruned
