# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-nonce-reuse-boundary-failure-in-mcp-tool-call-provenance-signing-under-concurrent-agent-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-nonce-reuse-boundary-failure-in-mcp-tool-call-provenance-signing-under-concurrent-agent-fan-out.warrant.json
# Markdown SHA-256:   898f422c924b1d635fdf5aab27a8aedb3f3a35c03d2b3a156cccece9afe2e44a
# Code AST SHA-256:   9659880272db5a79380cbf7aff5c381ce8835c7a4e92b595c174d92c01e1d101
# Verified Classes:   ProvenanceNonceCollision, DuplicateAttemptDispatch, SignedEnvelope, ProvenanceLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class ProvenanceNonceCollision(RuntimeError):
    """Raised when a signing context attempts to reuse a nonce across issuers."""
    pass


class DuplicateAttemptDispatch(RuntimeError):
    """Raised when a coordinator dispatches a second envelope for a terminal attempt."""
    pass


@dataclass
class SignedEnvelope:
    issuer: str
    args_hash: str
    attempt_id: str
    nonce: str
    timestamp: float


@dataclass
class ProvenanceLedger:
    """Coordinator-side ledger that bounds nonce reuse and duplicate dispatch."""
    seen_nonces: dict = field(default_factory=dict)      # nonce -> issuer
    attempt_status: dict = field(default_factory=dict)   # attempt_id -> status

    def register_nonce(self, issuer: str, nonce: str) -> None:
        prior = self.seen_nonces.get(nonce)
        if prior is not None and prior != issuer:
            raise ProvenanceNonceCollision(
                f"nonce {nonce!r} already bound to issuer {prior!r}, "
                f"refusing reuse by {issuer!r}"
            )
        self.seen_nonces[nonce] = issuer

    def check_dispatch(self, env: SignedEnvelope) -> None:
        status = self.attempt_status.get(env.attempt_id)
        if status == "ACCEPTED":
            raise DuplicateAttemptDispatch(
                f"attempt {env.attempt_id!r} already terminal (ACCEPTED); "
                f"refusing second dispatch of args_hash {env.args_hash!r}"
            )
        self.register_nonce(env.issuer, env.nonce)

    def mark(self, env: SignedEnvelope, status: str) -> None:
        self.attempt_status[env.attempt_id] = status


def sign_and_dispatch(
    ledger: ProvenanceLedger,
    issuer: str,
    args_hash: str,
    attempt_id: str,
    nonce: str,
    tool_is_idempotent: bool,
) -> SignedEnvelope:
    env = SignedEnvelope(
        issuer=issuer,
        args_hash=args_hash,
        attempt_id=attempt_id,
        nonce=nonce,
        timestamp=time.time(),
    )
    ledger.check_dispatch(env)

    # Simulated server replay cache keyed on (issuer, args_hash, nonce).
    server_key = hashlib.sha256(
        f"{issuer}|{args_hash}|{nonce}".encode()
    ).hexdigest()
    if server_key in _SERVER_REPLAY_CACHE:
        # Terminal: do NOT re-sign with a fresh nonce. Mark and surface.
        ledger.mark(env, "REPLAY_REJECTED")
        if not tool_is_idempotent:
            raise ProvenanceNonceCollision(
                f"replay rejected for non-idempotent tool on attempt "
                f"{attempt_id!r}; re-signing would duplicate side effects"
            )
        return env

    _SERVER_REPLAY_CACHE.add(server_key)
    ledger.mark(env, "ACCEPTED")
    return env


_SERVER_REPLAY_CACHE: set = set()
