# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-speculative-draft-plan-whose-verifier-vote-is-unanimous-but-whose-supporting-traces-diverge.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-speculative-draft-plan-whose-verifier-vote-is-unanimous-but-whose-supporting-traces-diverge.warrant.json
# Markdown SHA-256:   ba973bf6dd7d7b36843062c365c381dc8e405c31013149e0796d143aa07226dd
# Code AST SHA-256:   c8b953697a86dac2f72ab0680cbcc4f31b9fa5cc4cde22121b4cd361c960ed99
# Verified Classes:   TraceDivergenceError, StepJustification, VerifierVote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Hashable


class TraceDivergenceError(RuntimeError):
    """Raised when a unanimous verifier vote is backed by mutually inconsistent traces."""


@dataclass(frozen=True)
class StepJustification:
    step_id: Hashable
    preconditions: frozenset
    preserved_invariant: str

    def signature(self):
        return (self.preconditions, self.preserved_invariant)


@dataclass
class VerifierVote:
    verifier_id: str
    approved: bool
    trace: list  # list[StepJustification]
    shared_context_with_drafter: bool = False


def commit_plan(
    plan_steps: list,
    votes: list,
    downstream_dependents: dict,
    divergence_threshold: float = 0.0,
):
    approving = [v for v in votes if v.approved]
    if not approving:
        raise TraceDivergenceError("no approving votes; nothing to commit")

    # Correlated voters do not count as independent corroboration.
    independent = [v for v in approving if not v.shared_context_with_drafter]
    if len(independent) < 2:
        raise TraceDivergenceError(
            "unanimity is not corroboration: fewer than two independent verifiers"
        )

    # Group justifications per step across independent verifiers.
    per_step = {}
    for v in independent:
        for sj in v.trace:
            per_step.setdefault(sj.step_id, []).append(sj.signature())

    diverging_with_dependents = []
    diverging_without_dependents = []
    for step_id, sigs in per_step.items():
        distinct = set(sigs)
        if len(distinct) <= 1:
            continue
        if downstream_dependents.get(step_id):
            diverging_with_dependents.append(step_id)
        else:
            diverging_without_dependents.append(step_id)

    if diverging_with_dependents:
        raise TraceDivergenceError(
            "unanimous approval rejected: justification signatures diverge at "
            f"steps with downstream dependents {diverging_with_dependents}; "
            "agreement on output is coincidental, not corroborating"
        )

    if diverging_without_dependents:
        # Harmless to this plan, but the drafter will carry the ambiguity forward.
        return {
            "status": "escalate",
            "reason": "latent ambiguity at leaf steps",
            "steps": diverging_without_dependents,
        }

    return {"status": "commit", "plan": plan_steps}
