# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-delegation-chain-as-non-repudiable-when-a-replayed-taskid-collides-with-a-legitimately-re-delegate.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-delegation-chain-as-non-repudiable-when-a-replayed-taskid-collides-with-a-legitimately-re-delegate.warrant.json
# Markdown SHA-256:   2c76a9d3f7131bc859cfae7bd98d821b079c08ef77f4759eecca0f709bd10484
# Code AST SHA-256:   df9d59cb94517fce75ed7bc3368ad3b23a1b7445926ab854366a36ca29a37886
# Verified Classes:   DelegationReplayConflict, Envelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Tuple

class DelegationReplayConflict(RuntimeError):
    """Raised when an A2A envelope's identity cannot be resolved to a
    non-repudiable (taskId, warrantId, depth) triple."""
    pass

@dataclass(frozen=True)
class Envelope:
    task_id: str
    parent_task_id: str
    delegator_warrant_id: str
    delegation_depth: int
    nonce: str
    signature: bytes

# cache: triple -> (signer_warrant_id, nonce)
_replay_cache: Dict[Tuple[str, str, int], Tuple[str, str]] = {}

def admit(env: Envelope, verify_sig) -> None:
    triple = (env.task_id, env.delegator_warrant_id, env.delegation_depth)
    if not verify_sig(env):
        raise DelegationReplayConflict(f"bad signature on {triple}")

    if triple in _replay_cache:
        cached_signer, cached_nonce = _replay_cache[triple]
        if cached_nonce == env.nonce:
            raise DelegationReplayConflict(f"true replay of {triple}")
        # same triple, different nonce, same signer: idempotent retry
        return

    # depth-aliased collision: same task_id, different warrant/depth is NOT a replay
    for (tid, wid, depth), (signer, _) in _replay_cache.items():
        if tid == env.task_id and (wid, depth) != (env.delegator_warrant_id, env.delegation_depth):
            if signer == env.delegator_warrant_id:
                raise DelegationReplayConflict(
                    f"non-repudiation conflict: {env.task_id} signed by {signer} "
                    f"at depth {depth} and depth {env.delegation_depth}"
                )

    if env.delegation_depth > 0:
        parent_key = (env.parent_task_id, env.delegator_warrant_id, env.delegation_depth - 1)
        if parent_key not in _replay_cache:
            # out-of-order arrival: fetch parent, do NOT reject
            raise DelegationReplayConflict(f"parent {parent_key} not yet seen; fetch required")

    _replay_cache[triple] = (env.delegator_warrant_id, env.nonce)
