# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-signed-task-replay-across-a-rotated-a2a-agent-card-key.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-signed-task-replay-across-a-rotated-a2a-agent-card-key.warrant.json
# Markdown SHA-256:   0ba2fb721544d9775a30b26d29d931d928fbe93e667a7ef30376bfdee2cff0d4
# Code AST SHA-256:   aaead5ccd1cc65576467465408435d8852e993b0b2758612620fe23744e2675d
# Verified Classes:   KeyBindingViolation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class KeyBindingViolation(RuntimeError):
    """Raised when a signed lifecycle event is signed by a kid not bound to the task."""


def verify_lifecycle_event(event, task_binding, current_card, last_checkpoint_hash):
    """
    task_binding: dict with task_id, bound_kids (frozenset), context_id, card_revision
    current_card: dict with revision, jwks (kid -> key)
    """
    kid = event.kid
    if kid in task_binding["bound_kids"]:
        # Fast path: bound signer. Signature already verified upstream.
        return "advance"

    # Unbound kid: candidate rotation or substitution. Require all three signals.
    card_rev_ok = current_card["revision"] > task_binding["card_revision"]
    context_ok = event.context_id == task_binding["context_id"]
    artifact_ok = event.artifact_hash == last_checkpoint_hash

    if card_rev_ok and context_ok and artifact_ok:
        # Legitimate rotation: route to renegotiation, do NOT advance state.
        return "renegotiate"

    raise KeyBindingViolation(
        f"task={task_binding['task_id']} kid={kid} not bound; "
        f"card_rev_ok={card_rev_ok} context_ok={context_ok} "
        f"artifact_ok={artifact_ok} -> treating as substitution, quarantining"
    )
