# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-signed-peer-votes-as-inadmissible-when-the-voter-s-reasoning-trace-was-truncated-by-context-window-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-signed-peer-votes-as-inadmissible-when-the-voter-s-reasoning-trace-was-truncated-by-context-window-eviction.warrant.json
# Markdown SHA-256:   8612e03b57a0f192feae0183e295c11cebb8370614fd1bb143b7d382d8368666
# Code AST SHA-256:   6fe91a6146ac0b9d623971fddfbe22c7d3a0898b5a533de11e04847dabb08035
# Verified Classes:   InadmissibleVote, VoteEnvelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class InadmissibleVote(RuntimeError):
    """Raised when a signed vote's trace commitment does not cover the
    quorum decision function's load-bearing premise set."""
    pass


@dataclass
class VoteEnvelope:
    voter_id: str
    decision: str
    trace_root: str            # Merkle root of the trace the voter actually held
    trace_completeness: bool   # signed attestation: no load-bearing premise evicted
    premise_set_hash: str      # hash of premises the trace actually contains
    signature: str


def admit_vote(vote: VoteEnvelope,
               required_premise_hash: str,
               verify_sig) -> bool:
    if not verify_sig(vote):
        raise InadmissibleVote(f"{vote.voter_id}: signature invalid")

    # The sharp boundary: a signature-valid vote over a compacted trace is
    # NOT admissible. Provenance is a precondition, not an audit artifact.
    if not vote.trace_completeness:
        raise InadmissibleVote(
            f"{vote.voter_id}: trace_completeness=False — "
            f"context eviction occurred between premise ingestion and signing"
        )

    if vote.premise_set_hash != required_premise_hash:
        raise InadmissibleVote(
            f"{vote.voter_id}: premise_set_hash {vote.premise_set_hash[:12]}... "
            f"does not cover required {required_premise_hash[:12]}... — "
            f"vote is evidence-free w.r.t. the decision function"
        )

    return True


def tally_quorum(votes, required_premise_hash, verify_sig, threshold):
    admissible = []
    for v in votes:
        try:
            admit_vote(v, required_premise_hash, verify_sig)
            admissible.append(v)
        except InadmissibleVote:
            continue  # stall rather than launder provenance into the threshold
    if len(admissible) < threshold:
        raise InadmissibleVote(
            f"quorum stalled: {len(admissible)} admissible of {threshold} required; "
            f"{len(votes) - len(admissible)} votes excluded for trace degradation"
        )
    return admissible
