# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-signs-a-delegated-a2a-task-after-a-clock-skew-induced-nonce-regression.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-signs-a-delegated-a2a-task-after-a-clock-skew-induced-nonce-regression.warrant.json
# Markdown SHA-256:   3545bc2b1aa5f33d2c6de2a67027af1dd4e50f8eff41201ae1f1b3fd36f81a58
# Code AST SHA-256:   ca1e67b6a3b0fd5f043b6729625c36f5418af75e92441c67ae36eae2730b3c2d
# Verified Classes:   WarrantForkError, DelegationRefused, Warrant, ReplayLedger, Delegator
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass
from typing import Dict, Set, Tuple


class WarrantForkError(RuntimeError):
    """Raised when a task-scoped commitment is accepted under two distinct warrants."""


class DelegationRefused(RuntimeError):
    """Raised when a delegator attempts an unsafe re-sign after a freshness rejection."""


@dataclass(frozen=True)
class Warrant:
    task_id: str
    issuer: str
    seq: int
    nonce: str
    issued_at: float
    expires_at: float
    parent_warrant_hash: str
    task_commitment: str  # H(task_payload || root_nonce); immutable across hops


class ReplayLedger:
    """Per-issuer freshness ledger plus task-scoped commitment uniqueness."""

    def __init__(self) -> None:
        self._seq_floor: Dict[str, int] = {}
        self._seen_nonces: Set[Tuple[str, str]] = set()
        self._commitments: Dict[str, Tuple[str, Warrant]] = {}  # task_id -> (warrant_hash, warrant)

    @staticmethod
    def _hash(w: Warrant) -> str:
        blob = f"{w.task_id}|{w.issuer}|{w.seq}|{w.nonce}|{w.task_commitment}".encode()
        return hashlib.sha256(blob).hexdigest()

    def accept(self, w: Warrant, now: float) -> str:
        if now > w.expires_at:
            raise DelegationRefused(f"warrant expired at verifier: {w.expires_at} < {now}")

        # Freshness predicate (issuer-controlled; can regress under clock skew).
        floor = self._seq_floor.get(w.issuer, -1)
        if w.seq <= floor:
            raise DelegationRefused(
                f"NONCE_REGRESSION: seq {w.seq} <= floor {floor} for issuer {w.issuer}"
            )
        if (w.issuer, w.nonce) in self._seen_nonces:
            raise DelegationRefused(f"DUPLICATE_NONCE: {w.nonce} from {w.issuer}")

        # Uniqueness predicate (issuer-uncontrollable; the actual guardrail).
        prior = self._commitments.get(w.task_id)
        if prior is not None:
            prior_hash, prior_w = prior
            this_hash = self._hash(w)
            if prior_hash != this_hash:
                raise WarrantForkError(
                    f"task {w.task_id} already committed under {prior_hash[:12]} "
                    f"(nonce={prior_w.nonce}, issued_at={prior_w.issued_at}); "
                    f"refusing second acceptance under {this_hash[:12]} "
                    f"(nonce={w.nonce}, issued_at={w.issued_at})"
                )
            return prior_hash  # idempotent replay of the identical warrant

        self._seq_floor[w.issuer] = max(floor, w.seq)
        self._seen_nonces.add((w.issuer, w.nonce))
        h = self._hash(w)
        self._commitments[w.task_id] = (h, w)
        return h


class Delegator:
    """Mints and retries warrants; enforces the no-re-sign-without-quorum rule."""

    def __init__(self, issuer: str, ledger: ReplayLedger) -> None:
        self.issuer = issuer
        self.ledger = ledger
        self._sent: Dict[Tuple[str, str], Set[str]] = {}   # (task_id, parent_hash) -> verifiers sent to
        self._nonaccept: Dict[Tuple[str, str], Set[str]] = {}  # verifiers that returned REJECTED_NO_ACCEPTANCE

    def mint(self, task_id: str, parent_hash: str, commitment: str, seq: int, now: float) -> Warrant:
        key = (task_id, parent_hash)
        sent = self._sent.get(key, set())
        cleared = self._nonaccept.get(key, set())
        # The invariant: never mint a *fresh* warrant for a tuple unless every
        # verifier previously sent to has signed a REJECTED_NO_ACCEPTANCE.
        if sent and not sent.issubset(cleared):
            raise DelegationRefused(
                f"unsafe re-sign for task {task_id}: verifiers {sent - cleared} "
                f"have not confirmed no-acceptance; escalate instead of re-signing"
            )
        w = Warrant(
            task_id=task_id,
            issuer=self.issuer,
            seq=seq,
            nonce=f"n-{seq}-{now:.6f}",
            issued_at=now,
            expires_at=now + 300.0,
            parent_warrant_hash=parent_hash,
            task_commitment=commitment,
        )
        self._sent.setdefault(key, set()).add("verifier")  # placeholder for fan-out
        return w


def handle_rejection(
    delegator: Delegator,
    rejection_class: str,
    task_id: str,
    parent_hash: str,
    verifier: str,
    accepted_warrant_hash: str | None,
    prior_warrant_hash: str | None,
) -> str:
    key = (task_id, parent_hash)
    if rejection_class == "DUPLICATE_NONCE" and accepted_warrant_hash == prior_warrant_hash:
        return "RESEND_IDENTICAL"  # idempotency probe; safe
    if rejection_class in {"TRANSPORT_FAILURE", "VERIFIER_UNAVAILABLE"}:
        delegator._nonaccept.setdefault(key, set()).add(verifier)
        return "RESIGN_ALLOWED"
    if rejection_class in {"NONCE_REGRESSION", "SEQ_REGRESSION", "EXPIRED_AT_VERIFIER"}:
        # Freshness ambiguity: a prior acceptance may exist invisibly. Escalate.
        raise DelegationRefused(
            f"{rejection_class} on {task_id} from {verifier}: freshness ambiguity; "
            f"re-signing would fork the task-scoped commitment"
        )
    raise DelegationRefused(f"unclassified rejection {rejection_class}; refusing to guess")
