# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-peer-s-signed-envelope-despite-a-valid-signature-nonce-binding-collapse-under-a2a-replay-windows.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-peer-s-signed-envelope-despite-a-valid-signature-nonce-binding-collapse-under-a2a-replay-windows.warrant.json
# Markdown SHA-256:   6774a4b0ec356372857e612e15843023d78e8d10035de90a725013cca6d0657f
# Code AST SHA-256:   aee32ad59b98e9a00e446503ae95577be562e46a5b75ccb1e909527abf737de8
# Verified Classes:   EnvelopeRejected, NonceCollision, CrossSessionReplay, StaleAttempt, Envelope, ReplayCacheEntry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class EnvelopeRejected(RuntimeError):
    """Base class for admissible-but-rejected envelopes."""
    pass


class NonceCollision(EnvelopeRejected):
    """Same (sender, session, nonce) seen with a different payload digest."""
    pass


class CrossSessionReplay(EnvelopeRejected):
    """Nonce absent from cache but session_id does not match issuance scope."""
    pass


class StaleAttempt(EnvelopeRejected):
    """Attempt index does not exceed the recipient's committed index."""
    pass


@dataclass(frozen=True)
class Envelope:
    sender_id: str
    session_id: str
    nonce: str
    timestamp: float
    payload_digest: str
    attempt_index: int
    signature_valid: bool


@dataclass
class ReplayCacheEntry:
    payload_digest: str
    session_id: str
    committed_attempt: int


def admit_envelope(
    env: Envelope,
    cache: dict[tuple[str, str, str], ReplayCacheEntry],
    committed_attempt: int,
    now: float,
    window: float,
    skew_bound: float,
) -> None:
    if not env.signature_valid:
        raise EnvelopeRejected(f"signature invalid for {env.sender_id}")

    key = (env.sender_id, env.session_id, env.nonce)
    prior = cache.get(key)

    if prior is not None:
        if prior.payload_digest != env.payload_digest:
            # Quarantine both: generator reuse across distinct payloads.
            raise NonceCollision(
                f"nonce {env.nonce} bound to {prior.payload_digest} "
                f"but presented with {env.payload_digest}"
            )
        raise EnvelopeRejected(f"exact replay of nonce {env.nonce}")

    # Nonce unseen under this session; verify it was not issued elsewhere.
    for (sid, sess, n), entry in cache.items():
        if sid == env.sender_id and n == env.nonce and sess != env.session_id:
            raise CrossSessionReplay(
                f"nonce {env.nonce} issued under session {sess}, "
                f"presented under {env.session_id}"
            )

    if env.attempt_index <= committed_attempt:
        raise StaleAttempt(
            f"attempt {env.attempt_index} <= committed {committed_attempt}"
        )

    lo = now - window - skew_bound
    hi = now + skew_bound
    if not (lo <= env.timestamp <= hi):
        raise EnvelopeRejected(
            f"timestamp {env.timestamp} outside [{lo:.1f}, {hi:.1f}]"
        )

    cache[key] = ReplayCacheEntry(
        payload_digest=env.payload_digest,
        session_id=env.session_id,
        committed_attempt=env.attempt_index,
    )
