# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-revoked-agent-warrants-from-resurrecting-across-a2a-mesh-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-revoked-agent-warrants-from-resurrecting-across-a2a-mesh-hops.warrant.json
# Markdown SHA-256:   aaa1803265031dbaa3878623fd79988c7b0c82b6b9d333adb67555d556e3509b
# Code AST SHA-256:   821782d4e68cc7f1054868b02931e28f5903c69756c8db7027e4f4152e17abcd
# Verified Classes:   RevocationInvariantViolation, Warrant, HandoffEnvelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class RevocationInvariantViolation(RuntimeError):
    """Raised when a hop attempts to accept a warrant without an
    independently observed, in-budget liveness check (C2/C3 breach)."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    subject_key: str
    max_acceptance_age_s: int


@dataclass(frozen=True)
class HandoffEnvelope:
    warrant: Warrant
    # Provenance only. MUST NOT be consumed as an authorization decision.
    prior_acceptance_assertion: Optional[str] = None


def verify_hop(
    envelope: HandoffEnvelope,
    *,
    local_agent_key: str,
    revocation_source_reachable: bool,
    observed_liveness_age_s: Optional[int],
) -> bool:
    w = envelope.warrant

    # C1: warrant must be bound to this executing agent.
    if w.subject_key != local_agent_key:
        raise RevocationInvariantViolation(
            f"warrant {w.warrant_id} bound to {w.subject_key}, "
            f"not executing agent {local_agent_key}"
        )

    # C2: a peer's prior acceptance is provenance, never authority.
    # If any caller has wired it into the decision, that is the bug.
    if envelope.prior_acceptance_assertion is not None:
        # Explicitly ignored for authorization; retained for audit only.
        pass

    # C3: liveness must be observed by THIS hop, within budget.
    if not revocation_source_reachable:
        raise RevocationInvariantViolation(
            f"no revocation path for {w.warrant_id}; "
            f"fail-closed (REFUSE_PENDING), do not inherit peer trust"
        )
    if observed_liveness_age_s is None:
        raise RevocationInvariantViolation(
            f"no liveness observation for {w.warrant_id}"
        )
    if observed_liveness_age_s > w.max_acceptance_age_s:
        raise RevocationInvariantViolation(
            f"liveness observation stale by {observed_liveness_age_s}s "
            f"> budget {w.max_acceptance_age_s}s for {w.warrant_id}"
        )
    return True
