# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-after-an-a2a-v1-0-task-state-divergence-the-task-state-agentcard-skills-inputmodes-desynchronization-bo.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-after-an-a2a-v1-0-task-state-divergence-the-task-state-agentcard-skills-inputmodes-desynchronization-bo.warrant.json
# Markdown SHA-256:   e9a6972039ffdd79f3b1b0494295812eb420c4f68c6a79ca17dd7083f6a7c3e4
# Code AST SHA-256:   88928e8a9ba6ed182b16de7337a41a29c7da3b8c3482b1ee6d10c27d5e011d3b
# Verified Classes:   AgentCardDivergenceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class AgentCardDivergenceError(RuntimeError):
    """Raised when a peer's execution-time behavior contradicts its cached Agent Card."""
    pass


def reconcile_input_required(
    cached_card: dict,
    fresh_card: dict,
    task: dict,
    clarification_prompt: str,
) -> str:
    """
    Decide whether an `input-required` transition is legitimate or a card-divergence symptom.
    Returns "resubmit" or "abort_and_replan". Raises AgentCardDivergenceError on hard divergence.
    """
    if task.get("state") != "input-required":
        return "resubmit"

    cached_modes = {
        m
        for skill in cached_card.get("skills", [])
        for m in skill.get("inputModes", [])
    }
    fresh_modes = {
        m
        for skill in fresh_card.get("skills", [])
        for m in skill.get("inputModes", [])
    }

    dropped = cached_modes - fresh_modes
    if not dropped:
        # Card unchanged; the clarification is legitimate.
        return "resubmit"

    # The peer is asking for something its own (fresh) card no longer supports,
    # but our cache still claims it does. This is the divergence boundary.
    referenced = [m for m in dropped if m.split("/")[-1].lower() in clarification_prompt.lower()]
    if referenced:
        raise AgentCardDivergenceError(
            f"Peer requested input-required for modality {referenced} that its "
            f"fresh card dropped (cached={sorted(cached_modes)}, fresh={sorted(fresh_modes)}); "
            f"aborting task {task.get('id')} and re-planning against fresh card."
        )

    # Card narrowed but prompt doesn't reference the dropped modality: still
    # treat the cache as invalid and force re-plan, but do not hard-fail.
    return "abort_and_replan"


def verify_webhook_liveness(
    cached_card: dict,
    fresh_card: dict,
    polls_since_registration: int,
    max_silent_polls: int = 3,
) -> bool:
    """
    A webhook `set` acknowledgment is not proof of delivery. Trust it only if
    the fresh card still advertises pushNotifications and the task transitioned
    without polling. Raises if the capability was withdrawn mid-task.
    """
    if not cached_card.get("capabilities", {}).get("pushNotifications", False):
        return False

    if not fresh_card.get("capabilities", {}).get("pushNotifications", False):
        raise AgentCardDivergenceError(
            "pushNotifications withdrawn in fresh card but webhook was registered "
            "against cached card; registration is dead, must fall back to polling."
        )

    if polls_since_registration >= max_silent_polls:
        # Silent webhook: presume dead, force re-fetch + polling fallback.
        return False

    return True
