# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-withhold-a-byzantine-commit-vote-when-a-peer-s-task-commitment-proof-is-valid-but-its-provenance-chain-is-unverifia.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-withhold-a-byzantine-commit-vote-when-a-peer-s-task-commitment-proof-is-valid-but-its-provenance-chain-is-unverifia.warrant.json
# Markdown SHA-256:   80b63529db246ddf5260b2e39f3b2773fe244ca9f9eb4cf6460d9cc4397fe7d3
# Code AST SHA-256:   8fa557079b0ec78b7ff6cffd3709c4322e682c19c94f87ffafb62ba98245df66
# Verified Classes:   UnverifiableProvenanceError, ProvenanceConflictError, Vote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnverifiableProvenanceError(RuntimeError):
    """Raised when a commitment proof is signature-valid but its root_digest
    cannot be independently reconstructed from locally-held provenance."""
    pass


class ProvenanceConflictError(UnverifiableProvenanceError):
    """Raised when local cached prefix reconstructs a *different* root_digest."""
    pass


@dataclass
class Vote:
    decision: str          # "yes" | "no" | "withhold"
    reconstructs: bool     # did this agent locally recompute root_digest?


def evaluate_commitment_vote(
    proposal_digest: str,
    tail_sigs_valid: bool,
    root_digest: str,
    local_prefix: Optional[list],   # cached (step_id, tool, in_digest, out_digest)
    tail_steps: list,
    context_budget_remaining: int,
    steps_needed: int,
) -> Vote:
    if not tail_sigs_valid:
        return Vote(decision="no", reconstructs=False)

    if local_prefix is None:
        # Cannot reconstruct: withhold, request prefix. Do NOT vote yes.
        raise UnverifiableProvenanceError(
            f"root_digest {root_digest[:12]} unverifiable: no local prefix; "
            "withhold and fetch prefix before voting"
        )

    if context_budget_remaining < steps_needed:
        # Budget exhaustion mid-walk is a silent-truncation hazard.
        raise UnverifiableProvenanceError(
            f"cannot walk {steps_needed} provenance steps with "
            f"{context_budget_remaining} tokens remaining; refusing partial verify"
        )

    reconstructed = _hash_chain(local_prefix + tail_steps)
    if reconstructed != root_digest:
        raise ProvenanceConflictError(
            f"local prefix reconstructs {reconstructed[:12]} != "
            f"committed {root_digest[:12]}: ambiguous prefix, abstain"
        )

    return Vote(decision="yes", reconstructs=True)


def finalize_commitment(votes: list[Vote], f: int) -> bool:
    reconstructing_yes = sum(1 for v in votes if v.decision == "yes" and v.reconstructs)
    if reconstructing_yes < 2 * f + 1:
        # Signature-only yes-votes do not count toward finality.
        return False
    return True


def _hash_chain(steps: list) -> str:
    h = ""
    for step in steps:
        h = f"{h}|{step}"
    return str(hash(h))
