# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bind-its-signing-key-to-the-delegated-task-instance-not-the-agent-identity-to-survive-vote-replay-across-consensus-rounds.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bind-its-signing-key-to-the-delegated-task-instance-not-the-agent-identity-to-survive-vote-replay-across-consensus-rounds.warrant.json
# Markdown SHA-256:   44117d938e60f312d39e40496a4ae82094bacf698207be168ace5130eb7fa596
# Code AST SHA-256:   50158b64d084af1c31171a5a637abcb9ec1cbd3ca5985d27925bd1ddb3fa5ed9
# Verified Classes:   WarrantReplayError, Warrant, PeerSigner, Auditor
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class WarrantReplayError(RuntimeError):
    """Raised when a peer is asked to sign a warrant nonce it has already signed,
    or when an auditor admits a vote whose nonce is consumed/unknown."""


@dataclass(frozen=True)
class Warrant:
    agent_id: str
    task_id: str
    round_id: int
    attempt: int
    nonce: str

    def digest(self) -> str:
        raw = f"{self.agent_id}|{self.task_id}|{self.round_id}|{self.attempt}|{self.nonce}"
        return hashlib.sha256(raw.encode()).hexdigest()


class PeerSigner:
    """Signs votes bound to a warrant instance, with a local replay guard."""

    def __init__(self, agent_id: str):
        self.agent_id = agent_id
        self._signed_nonces: set[str] = set()

    def sign_vote(self, warrant: Warrant, vote_value: str) -> str:
        if warrant.agent_id != self.agent_id:
            raise WarrantReplayError(
                f"warrant agent {warrant.agent_id} != signer {self.agent_id}"
            )
        if warrant.nonce in self._signed_nonces:
            # The cached-warrant bug surfaces here instead of as a silent livelock.
            raise WarrantReplayError(
                f"nonce {warrant.nonce} already signed by {self.agent_id}; "
                f"orchestrator must mint a fresh warrant per attempt"
            )
        self._signed_nonces.add(warrant.nonce)
        payload = f"{warrant.digest()}|{vote_value}"
        return hashlib.sha256(payload.encode()).hexdigest()


class Auditor:
    """Admits votes by resolving scope from its own warrant ledger, never the wire."""

    def __init__(self):
        self._ledger: dict[str, Warrant] = {}
        self._consumed: set[str] = set()

    def issue(self, warrant: Warrant) -> None:
        self._ledger[warrant.nonce] = warrant

    def admit(self, wire_nonce: str, wire_round_claim: int, vote_value: str) -> None:
        warrant = self._ledger.get(wire_nonce)
        if warrant is None:
            raise WarrantReplayError(f"unknown nonce {wire_nonce}")
        if wire_nonce in self._consumed:
            raise WarrantReplayError(
                f"nonce {wire_nonce} already consumed; replay rejected"
            )
        if warrant.round_id != wire_round_claim:
            raise WarrantReplayError(
                f"wire round claim {wire_round_claim} != ledger round "
                f"{warrant.round_id} for nonce {wire_nonce}"
            )
        # Dedup keyed on nonce: consumption of this warrant cannot poison
        # any other round's slot for the same agent.
        self._consumed.add(wire_nonce)


def run_retry_round() -> None:
    signer = PeerSigner("P1")
    auditor = Auditor()

    w7 = Warrant("P1", "task-42", round_id=7, attempt=1, nonce="n-7-1")
    auditor.issue(w7)
    signer.sign_vote(w7, "APPROVE")
    auditor.admit(w7.nonce, 7, "APPROVE")

    # Orchestrator retry: must mint a fresh nonce. Simulate the cached-warrant bug.
    stale = w7  # bug: retry re-sends the original warrant
    try:
        signer.sign_vote(stale, "APPROVE")
    except WarrantReplayError as e:
        raise WarrantReplayError(
            f"retry path reused warrant nonce {stale.nonce}; "
            f"livelock prevented, but orchestrator must be fixed: {e}"
        ) from e


if __name__ == "__main__":
    run_retry_round()
