# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-sign-a-result-attestation-when-a-byzantine-quorum-of-peer-agents-reports-agreement-but-the-local-repl.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-sign-a-result-attestation-when-a-byzantine-quorum-of-peer-agents-reports-agreement-but-the-local-repl.warrant.json
# Markdown SHA-256:   e62733a3f690f6fef9ac53f40d304a230ebee0dd4eb7afeb38ddcb9172ee8abb
# Code AST SHA-256:   cd888c8ff35e3b8b58682e2418d07754a68946feefd2cc2d42558feebfadab7f
# Verified Classes:   ReplayDivergenceError, CommitRecord, QuorumState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ReplayDivergenceError(RuntimeError):
    """Raised when an agent's local replay digest diverges from its commit digest
    outside the declared nondeterminism envelope, at a pivotal attestation position."""
    pass


@dataclass
class CommitRecord:
    task_id: str
    subtask_id: str
    plan_hash: str
    tool_transcript_digest: str
    declared_nondeterministic_tools: frozenset


@dataclass
class QuorumState:
    threshold: int
    attestations_received: int
    total_agents: int

    def is_pivotal(self) -> bool:
        # Pivotal if this agent's attestation is needed to reach threshold
        # and quorum has not already been reached without it.
        return self.attestations_received == self.threshold - 1


def canonical_transcript_digest(transcript: list[dict]) -> str:
    h = hashlib.sha256()
    for call in transcript:
        h.update(call["tool"].encode())
        h.update(b"\x00")
        h.update(repr(call["output"]).encode())
        h.update(b"\x00")
    return h.hexdigest()


def attest_result(
    commit: CommitRecord,
    replay_transcript: list[dict],
    quorum: QuorumState,
    divergent_tools: set[str],
    reconciliation_executed: bool,
) -> str:
    # CRITICAL: compute replay digest BEFORE inspecting quorum state,
    # to prevent anchoring on the majority value.
    replay_digest = canonical_transcript_digest(replay_transcript)

    if replay_digest == commit.tool_transcript_digest:
        return "ATTEST"

    # Divergence detected. Classify against declared envelope.
    outside_envelope = not divergent_tools.issubset(
        commit.declared_nondeterministic_tools
    )

    if not outside_envelope and reconciliation_executed:
        return "ATTEST_WITH_DIVERGENCE_ACK"

    if not quorum.is_pivotal():
        # Non-pivotal divergence: refuse silently to audit, do not block.
        return "REFUSE_LOG_ONLY"

    # Pivotal divergence outside envelope: refuse AND broadcast.
    # Silent abstention here would let view-change substitute a Byzantine agent.
    raise ReplayDivergenceError(
        f"Pivotal replay divergence on task={commit.task_id} "
        f"subtask={commit.subtask_id}: commit_digest={commit.tool_transcript_digest[:12]} "
        f"replay_digest={replay_digest[:12]} divergent_tools={sorted(divergent_tools)}. "
        f"Refusing attestation and broadcasting DIVERGENCE_BROADCAST. "
        f"Do not abstain silently — broadcast reason so peers can independently verify."
    )
