# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-equivocation-and-honest-dissent-in-byzantine-task-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-equivocation-and-honest-dissent-in-byzantine-task-commitment.warrant.json
# Markdown SHA-256:   910beb87313aa8a6263cd6ecb338c7b5c3fc6a6be855b8915f1bd569e1dd26c0
# Code AST SHA-256:   b51c457b03fdddc4957d8e75e81b9b5a27b9f76c87c3c2eae0d892836cd6abef
# Verified Classes:   SemanticEquivocationError, ArtifactHashMismatchError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json


class SemanticEquivocationError(RuntimeError):
    """Raised when a single committer signs two semantically distinct
    commitments for the same task, even though each signature verifies."""


class ArtifactHashMismatchError(RuntimeError):
    """Raised when delivered artifact bytes do not match the hash bound
    into the quorum certificate that finalized the commitment."""


def canonical_scope_hash(scope: dict) -> str:
    # Sorted keys, explicit nulls, no free-text fields permitted.
    forbidden = {"notes", "rationale", "caveats"}
    if forbidden & scope.keys():
        raise SemanticEquivocationError(
            f"scope contains non-canonical free-text fields: {forbidden & scope.keys()}"
        )
    blob = json.dumps(scope, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def classify_vote(sender: str, task_id: str, scope: dict, vote_log: dict) -> str:
    scope_hash = canonical_scope_hash(scope)
    prior = vote_log.setdefault((sender, task_id), set())
    prior.add(scope_hash)
    if len(prior) > 1:
        raise SemanticEquivocationError(
            f"sender {sender} signed {len(prior)} distinct canonical scopes "
            f"for task {task_id}: {sorted(prior)}"
        )
    return scope_hash


def verify_finalized_artifact(qc: dict, delivered_bytes: bytes) -> None:
    actual = hashlib.sha256(delivered_bytes).hexdigest()
    if actual != qc["artifact_hash"]:
        raise ArtifactHashMismatchError(
            f"QC attested {qc['artifact_hash']} but delivered bytes hash to {actual}; "
            f"treat as Byzantine event attributable to committers {qc['signers']}"
        )
