# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-push-notification-binding-before-its-agent-card-is-re-signed.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-push-notification-binding-before-its-agent-card-is-re-signed.warrant.json
# Markdown SHA-256:   876df818c15cbe78ed53028153c51c08f6a7ad79bde1d63411c9352fbd9c2fdc
# Code AST SHA-256:   600491fb538f50429e80b0f949d9e97b1f7a9e0e9bdbb9c3ae034d223a4676c3
# Verified Classes:   BindingAuthoritySkew
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class BindingAuthoritySkew(RuntimeError):
    """Raised when a push-notification binding outlives the card authority that created it."""
    pass


AUTHORITY_FIELDS = ("pushNotifications", "security", "allowedOrigins")


def _authority_delta(card_old: dict, card_now: dict) -> set:
    delta = set()
    for field in AUTHORITY_FIELDS:
        if card_old.get(field) != card_now.get(field):
            delta.add(field)
    return delta


def dispatch_terminal_event(task: dict, binding: dict, card_old: dict, card_now: dict) -> str:
    if card_old.get("version") == card_now.get("version"):
        return "deliver"

    delta = _authority_delta(card_old, card_now)
    if not delta:
        return "deliver"

    # Authority-bearing field changed: re-check the binding against the live card.
    allowed = card_now.get("allowedOrigins", [])
    still_valid = any(binding["url"].startswith(origin) for origin in allowed)
    if still_valid and card_now.get("pushNotifications") is True:
        return "deliver_resigned"

    # Binding no longer satisfies the current card. Do NOT retry.
    raise BindingAuthoritySkew(
        f"binding {binding['url']} for task {task['taskId']} created under card "
        f"{card_old.get('version')} is invalid under {card_now.get('version')} "
        f"(delta={sorted(delta)}); refusing delivery and retry"
    )
